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/application.rb
...
module MyApp
class Application < Rails::Application
...
ActiveSupport.encode_big_decimal_as_string = true
...
end
end
Rails 3: Just add this monkey patch to your initializers:
# 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: