Currency, Money, and Rails 3.1

I recently added a rake task to generate large amounts of random entries so that I could start to test out Regdel in a more real-world scenario.

So far adding a hundred or so entries is fine, but in the process I ran into some minor issues regarding floats. For example, an amount like “$187.67” might display like “187.6700000001”, or something like that.

I had tried to avoid this by storing the entry amount as an integer and overriding the accessors to multiple the amount entered by 100 when writing and dividing by 100 when reading. That worked OK, but when I would sum the amounts, since they were already floats, things would get a bit messed up.

I did some research to find out if there are any tools for Rails 3.1 to handle this type of stuff and thankfully I found the number_to_currency helper. I also discovered that Rails supports decimals as a primitive data type. I decided against that for portability.

By Albert on September 4, 2011 5:11 PM

Categories: