with a 52-bit mantissa and an 11-bit exponent (the IEEE 754 Standard for storing numeric values).
This internal representation of numbers may cause unexpected results like the above.
Most integers greater than 253 = 9007199254740992 cannot be represented exactly in this format.
Likewise, many decimals/fractions, such as 0.362, cannot be represented exactly,
leading to the perceived "inaccuracy" in the above example.
To avoid these "inaccurate" results, you might want to round the results
to the precision of the data you used.
Example: In order to round the result of the multiplication
to one thousandth, you can use the following code
document.write statements have been inserted after each line of code to show intermediate results):
rawX = 0.362*100 // number close to 36.2
document.write(rawX) // 36.199999999999996
roundedX = Math.round(1000*rawX)/1000 // number even closer to 36.2
document.write(roundedX) // 36.2
resultStr = roundedX.toFixed(3) // string '36.200'
document.write(resultStr) // 36.200
(when we output the result
rawX, we do not get
36.2, but rather
Less obvious is the fact that even after we use the
Math.round method and then divide by
roundedX is not necessarily an exact result, either.
(Indeed, the decimal
36.2 is not exactly representable in the IEEE 754 format.)
However, the result
roundedX = Math.round(1000*rawX)/1000 is more accurate than
roundedX is so close that calling
36.2 as expected.
'36.200' as expected.
In summary: You can use
Math.round either alone or in combination
to get rid of the perceived "inaccuracy" and, if necessary,
n decimal places in the result.