Created
December 29, 2011 04:43
-
-
Save mbailey/1531950 to your computer and use it in GitHub Desktop.
Should I not use ruby to add dollar values?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Thanks Michael! I'm surprised I've not noticed that before. :-)
NP! Also interesting: http://en.wikipedia.org/wiki/0.999...
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.
@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
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"