Make Rails Json Output Decimal Numbers Instead Of Strings

Posted By Weston Ganger

Working on an application I noticed that when getting JSON data from Rails the decimal numbers come as strings. Turns out this is to ensure it is still accurately rounded.

If you don't care about the rounding of large numbers then you can force Rails to output the decimals as numbers.

Rails 4 & 5: Just add the following configuration option:

# config/initializers/big_decimal_json_patch.rb
require 'bigdecimal'

class BigDecimal
  def as_json(options = nil) #:nodoc:
    if finite?
      self
    else
      NilClass::AS_JSON
    end
  end
end

Related External Links:

Article Topic:Software Development - Ruby / Rails

Date:September 08, 2016