Skip to content

Instantly share code, notes, and snippets.

@mbailey
Created December 29, 2011 04:43
Show Gist options
  • Save mbailey/1531950 to your computer and use it in GitHub Desktop.
Save mbailey/1531950 to your computer and use it in GitHub Desktop.
Should I not use ruby to add dollar values?
mbailey@oasis:~ $ irb
1.9.2p290 :001 > 120.82+15.96+135.50
=> 272.28
1.9.2p290 :002 > 120.82+15.96+135.51
=> 272.28999999999996
@mipearson
Copy link

ruby-1.9.3-p0 :001 > 120.82+15.96+135.51 => 272.28999999999996 ruby-1.9.3-p0 :002 > sprintf("%0.2f", 120.82+15.96+135.51) => "272.29"

@mbailey
Copy link
Author

mbailey commented Dec 29, 2011

Thanks Michael! I'm surprised I've not noticed that before. :-)

@mipearson
Copy link

NP! Also interesting: http://en.wikipedia.org/wiki/0.999...

@seancaffery
Copy link

I think that you should use two fields; a dollar and a cent amount.
I have have to change the way that I dealt with money values recently due to similar issues in the database.

@mipearson
Copy link

@seancaffery: I disagree. Use a dedicated fixed-point decimal class or represent all monetary amounts internally as their smallest possible fraction. Eg, represent $100.00 as 10000, or two dollars fifty as $2.50.

If you get into a situation where you need to divide the amount, clever use of floor and ceil will ensure you have no leftovers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment