BinaryWebPark

Formatting Ruby’s BigDecimal For API Calls

June 30, 2016

Formatting Ruby’s BigDecimal values in a Ruby API

Picture of currency

So while working on the largest production codebase I have ever worked on at a recent job, I ended up using a gem for dealing with money and currency (the Ruby money gem) that at one point seemed to return values in BigDecimal format, whereas previously it was being returned as a well-formatted string such as “7.05”.

Money-rails was not an option

The money-rails gem was not an option as this was a pure Ruby API solution. If I recall correctly, later I found out there was already a gem (I think it was monetize) that would help format BigDecimal values “automagically”. But that wasn’t an option at the time since I didn’t know about it!

So I used the following trick to get the format I needed:

dollars = BigDecimal.new('7.77777777') #this
formatted_dollars = dollars.truncate(4).to_s('F')

And now monies can be calculated

The truncate method truncates the value to n (in this case n=4) decimal places and the to_s method with an F argument means convert the value to a string with conventional floating point notation.

It’s pretty simple but it worked as an interim solution for what I needed.