Which is the deeper truth? Don't use..
Floats for money are fine, if done right (use cent as the base value, i.e., store $0.01 as 1.0e0). You get 53 bits of precision, and graceful overflow behaviour.
-
-
Doesn't that break down the moment you need to do any calculations?
-
Not at all, no.
-
How much do you owe on a $1 transaction with 4.9% sales tax? Under this scheme, you'd represent this as 100¢ × 104.9%, which gets you a value that is close to but not equal to 104.9.pic.twitter.com/6yTcN8s7Zm
-
You check your local applicable law to see what rounding mode you need to apply, and apply that to get back to full cents.
-
Note that actually knowing the fractional part (up to a certain precision) allows you to apply the correct rounding mode, unlike what happens when calculating using integers, where truncation always happens.
-
In my experience, "use floating-point, manage the bookkeeping yourself, and pray you don't get unlucky with error propagation" is much more prone to errors than "use a decimal type".
-
Until you hit an integer overflow, and things go belly up in pretty dramatic ways.
-
But my entire point here is that using floats is perfectly fine for money, if you follow a small number of rules, whereas using regexes for HTML parsing is bound to fail due to HTML being a recursive language, and regexes recognizing regular languages.
- 7 more replies
New conversation -
-
-
Graceful as in > double.MaxValue + 1 == double.MaxValue true

-
Yep. If you own quadrillions, a cent doesn't make a difference. Compare to 2147483648+1 though.
End of conversation
New conversation -
-
-
A float is 32 bits, normally. I find it hard to believe you can cram 53 bits of precision in there...
-
Use a double, obviously.
End of conversation
New conversation -
-
-
What about 3 and 4 digit currencies?
-
They have been mostly abandoned, but always go for the smallest subdivision in any case.
End of conversation
New conversation -
-
-
Until you forgot to apply biased rounding at the relevant places...
Thanks. Twitter will use this to make your timeline better. UndoUndo
-
Loading seems to be taking a while.
Twitter may be over capacity or experiencing a momentary hiccup. Try again or visit Twitter Status for more information.