Math Error in JavaScript

Believe it or not, if you do this in JavaScript: 103 x 67.12, you will get 6913.360000000001. This happens on both Microsoft Internet Explorer and Firefox. Try this your self.

Basic Math Errors in JavaScript

The calculation… Should equal… Your browser’s
81.66 * 15 1224.9
103 * 67.12 6913.36
24.88 + 4.35 29.23

In terms of mathematical accuracy, 81.66 times 15 unequivocally equals 1224.9, as any sixth grader with a pencil and a piece of paper can demonstrate. But computer is in binary world. it has to convert decimal to binary number before calculation and there may be a problem to convert floating point decimal to binary. This is same for all computer languages. To avoid this, you need to know the scale (the number of decimal positions). Then you can convert the floating point decimal to an integer and scale it back at the end. i.e. (67.12 * 100) * 103 / 100. In Java, BigDecimal can be used to setup the scale.

JavaScript has a built-in method – toFixed, can be used to fix this issue easily as well.

amount = 103 * 67.12;
result = amount.toFixed(2);

So don’t forget this when you deal with a floating point decimal even for addition or multiplication.

Leave a Reply