Me The Works of Wellyson Freitas

Fixing JavaScript arithmetics

Press F12 and type at the console:

0.1 + 0.2

The result is not what we usually expect. This is not a problem only with JavaScript, but a well-known issue in Computer Science. The same way the decimal system cannot represent 1/3 exactly, the binary system used by computers has problems with some floating numbers.

Take a look on this list: It's everywhere. The problem is that when we add numbers in many programming languages, the computer first converts them into their binary representation, performs the addition in binary, and then converts the result back to decimal.

A few years ago I remember facing this issue while working in the front-end of a financial module. With Java, we can use BigDecimal to get rid of this problem. In JavaScript, there is no native solution, and you should probably use libraries such as Decimal.js. But I just didn't want to use that.

One way of approaching this problem would be converting the floating numbers to integers. JavaScript does not have these problems operating with integers. It could be done just removing the decimal sign. After the operation, you can just put it back.

Just don't use round to solve this.