opensoul.org

Money with precision

I’ve been working on a project that needs to store mileage reimbursement rates to the nearest tenth of a cent. We were using the money gem, which stores money amounts in cents, so it looked like it was going to be a pain.

But without too much suffering, I modified the money gem to take a precision (in powers of 10), which defaults to 2. It can now store amounts in any precision.

>> amount = 20.to_money + 0.505.to_money
=> #<Money @precision=3, @currency="USD", @cents=20505>
>> amount.to_s
=> "20.505"
>> amount.format
=> "$20.51"

You can also store amounts in negative precisions, like millions:

>> amount = Money.new(50, 'USD', -6)
>> amount.to_s
=> "50"
>> amount.format
=> "$50000000.00"

Check out our fork of the money gem on github. There are lots of other goodies in there.

fork, gem, github, money, and ruby October 18, 2008

2 Comments

  1. Infakta Infakta October 21, 2008

    Is your gem public right now?

  2. Brandon Brandon October 21, 2008

    Infakta,

    The gem isn’t building on github right now, but once it does, you can run:

    $ gem install collectiveidea-money --source http://gems.github.com
    

    For now, you can download the source from github and run:

    $ rake gem
    

Post a Comment

Comments use textile. Anonymous comments will be deleted.

My name is Brandon Keepers. I like to build things, usually in Ruby or JavaScript. I work at GitHub and live in Holland, MI.

Popular Posts