Simple example of a floating point precision error for monetary amounts
Most software engineers are aware that floating point numbers are not suitable for monetary amounts, or any amount requiring reliable decimal precision.
It’s nice to have a quick and simple example of this, so here’s an operation that will break with floating point numbers in many languages including JavaScript:
1.01 - 0.42
// → 0.5900000000000001
In JavaScript and TypeScript, the big.js library is good for decimal operations.
In SQL, it’s best to store monetary and other decimal amounts as DECIMAL
, e.g.
DECIMAL(10,2)
.
Note that there’s a common misconception that you shouldn’t use the number type
in JSON for decimal amounts, due to these precision errors. However, JSON
itself is just a string, so despite the JavaScript Number
type being a
floating point implementation, it’s not accurate to describe JSON numbers as
being floating point. They’re just strings.
Floating point precision issues only occur when a decimal number is operated on
naively in JavaScript other languages. Sending a decimal representation over
the wire as {"fooNumber" 123.45}
is fine so long as the receiver handles it
correctly.