Hacker Newsnew | comments | show | ask | jobs | submit login

"Eich: No one expects the rounding errors you get - powers of five aren't representable well. They round poorly in base-two. So dollars and cents, sums and differences, will get you strange long zeros with a nine at the end in JavaScript. There was a blog about this that blamed Safari and Mac for doing math wrong and it's IEEE double -- it's in everything, Java and C"

-Peter Seibel Interview with Brendan Eich "who under intense time pressure, created JavaScript", Coders at Work, p.136




Some languages have arbitrary precision types or use BCD. Next time you see someone using floating point types for money, please stop them. There's too many financial libraries out there like OFX4J which get this wrong (or at least did the last time I looked).

-----


Python has Decimal for that. Unfortunately, the people who wrote the platform I use - which deals with money - decided they're "too slow".

-----


> Unfortunately, the people who wrote the platform I use - which deals with money - decided they're "too slow".

I've had the same problem (that platform wouldn't ha. It's… annoying (also bullshit: in the worst case — CPython <= 3.2 — basic arithmetic operations will take ~20µs on my machine aside from divisions which take a bit more and if that shows up in profiling use cdecimal, CPython 3.3 [integrated cdecimal] or pypy)

-----


If you don't have decimal types, then use fixed point. Or in simpler terms store cents (as integers) not dollars (as floats).

Then add a decimal point when you display.

If you are dealing with stocks or interest I suggest storing tenths, or hundreds of a cent to avoid rounding errors.

-----


Shitty when your language doesn't have integers then, eh?

-----


Javascript floats (all 64 bit floats actually) can store exact integers to 53 bits.

Which is enough for even the united states national budget, let alone more prosaic uses.

-----


> Next time you see someone using floating point types for money

... apply that logic to their paycheck and let them deal with being underpaid by a bizarre amount because of rounding.

Or apply it to their investment accounts so the errors accumulate for a few decades.

Nothing like an object lesson to remedy bad behavior.

-----




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact

Search: