In JavaScript, Python, and possibly other languages, if you round the value 37.305
to 2 decimal places, you get the wrong value:
Number(37.305).toFixed(2) => 37.30 // Should be 37.31
One solution to the precision problems when representing money is to use micros. That is, $1.00 => 1,000,000 micros.
My question is: how could I round the value representing $37.305 in micros (37305000
) to 2 decimal places (where the result should be 37.31
?
To round a representation (in micros) R to n decimal places (in the represented value):
The above suffices for non-negative R. To support negative numbers, adjustments may be needed for selecting the residue and applying the rounding rule to select s. These are fairly simple but depend on what residue or remainder operations are convenient in the programming language being used and on what rounding rule is desired.