JS floating point causing incorrect rounding

javascript, math

Solution

I ended up using math.js to do mathematical operations and that solved all my floating point issues.

The advantage of this lib was that there was no need to instantiate any sort of Big Decimal object (even though the lib does support BigDecimal). It was just as simple as replacing `Math` with `math` and passing the precision.

Problem

I have what may be an edge case scenario. When trying to round the value `4.015` to 2 decimal places, I always end up with `4.01` instead of the expected `4.02`. This happens consistently for all numbers with `.015` as the decimal portion. I round using a fairly common method in JS: ``` val = Math.round(val * 100) / 100; ``` I think the problem starts when multiplying by 100. The floating point inaccuracy causes this value to be rounded down rather than up. ``` var a = 4.015, // 4.015 mult = a * 100, // 401.49999999999994 (the issue) round = Math.round(mult), // 401 result = round / 100; // 4.01 (expected 4.02) ``` Fiddle: http://jsfiddle.net/eVXRL/ This problem does not happen if I try to round `4.025`. The expected value of `4.03` does return; it's only an issue with `.015` (so far). Is there a way to elegantly resolve this? There is of course the hack of just looking for `.015` and handling that case one-off, but that just seems wrong!

Original source