As far as I've read, best practice with managing money in Javascript is to represent all values scaled to the lowest possible denomination (e.g. $12.45 is scaled by 100 and represented as 1245
in our code, not 12.45
), and then round values to the nearest whole number when calculating.
However, we still run into problems when doing calculations on our values.
For example: a user pays $28.75, but uses a 30% discount.
We deal with this like so: Math.round(2875 * .7)
. But this calculates a result of 2012 (incorrect). This is because:
- In real life,
2875 * .7 = 2012.5
, which rounds to 2013 - In Javascript,
2875 * .7 = 2012.4999999999998
, which rounds to 2012
What is the best way of preventing this kind of error?