David - Musings of an SRE

How to fix BigDecimal returning as Strings in Rails

Something that I’ve just found out recently.

Basically, Rails serializes BigDecimal objects as JSON strings because they didn’t want its values to be misintepreted when deserialized.

But in Rails 4.0.x, an option to reverse that behavior was introduced in the form of:

  # config/application.rb
  ActiveSupport.encode_big_decimal_as_string = false # default = true

If you’re on Rails 4.0.x, adding the above will ensure that the values returned will be numbers.

If your Rails API is providing response data that contains numbers, you want to make sure that you are not accidentally encoding big decimals as string, which would cause a problem when trying to do arithmetic calculations with it.

ie, by default, BigDecimals are encoded as Strings, so when your output value is being used to add numbers like in javascript, you might experience something like this:

var responseDataNumber = "0.15";
var addition = 1 + responseDataNumber;
console.log(addition); // returns 10.15 instead of 1.15

So if you’re dealing with quite a lot of numbers output, you really should remember to set the flag to false


Note:

In Rails 4.1.x, the JSON encoder has been rewritten and the old ActiveSupport JSON Encoder has been released as a seperate gem.

To get this to work again, just add the following in your Gemfile.


# Gemfile
gem 'activesupport-json_encoder', github: 'rails/activesupport-json_encoder'

If you find this helpful, do share it around, or leave comments in the disqus below!