Trade prices
were kept to a tenth of a penny.
Screws by the hundred,
cable by the metre,
2.675 a unit.
The quote page
rounded each line for display.
price.toFixed(2)
The finance system
rounded the same line
when it raised the invoice.
Half up,
in decimal,
the way an accountant would.
Most lines agreed.
Some did not.
The quote said 2.67.
The invoice said 2.68.
A penny a line,
on a few hundred lines,
on a big order.
Customers noticed
before anybody in the office did.
The quote is what we agreed,
they said.
They were not wrong.
Here is the mechanism.
The page never held 2.675.
A JavaScript number
is a binary fraction,
and most decimal fractions
have no exact binary form.
Like a third in decimal,
they go on forever,
so the nearest one that fits
is stored instead.
Ask for it in full.
(2.675).toPrecision(20)
2.6749999999999998224
Just under the halfway point.
toFixed did its job perfectly.
It rounded the number it was given,
and the number it was given
was below half.
So it went down.
The finance system
worked in true decimals,
saw exactly 2.675,
and went up.
Both were correct.
They were rounding
two different numbers
that printed the same.
It is not only JavaScript.
Python's round(2.675, 2)
also gives 2.67,
and its documentation
uses that very example.
The fix is not
a cleverer rounding trick
on the page.
Adding a tiny amount before rounding
moves the problem
to a different set of prices.
Decide where money is calculated,
and calculate it there,
once.
In decimal arithmetic,
or in whole units of the smallest coin,
never in binary fractions.
Then send the page
the finished amounts,
already rounded,
as strings or as integer pennies.
The page displays money.
It does not decide it.
And test with the prices
that sit exactly on a half.
2.675.
1.005.
A test full of round numbers
passes for the wrong reason.
Whenever two systems
must agree on a number,
check that they are holding
the same number,
not just showing the same digits.
– Serguey Asael Shinder
Top comments (0)