Discover the solution to fixing decimal arithmetic in JavaScript.
When performing addition or subtraction involving decimal numbers in JavaScript, you may encounter unexpected results.
For instance, when adding 0.1 + 0.1
, the expected result of 0.2
is obtained. However, when adding 0.1 + 0.2
, the result is not 0.3
but rather 0.30000000000000004
. Similarly, subtracting 1.4 - 1
gives the result 0.3999999999999999
.
You might be wondering why this happens. It is not specific to JavaScript but is a common occurrence in most programming languages. The reason lies in the fact that computers store data in binary format, using 0
and 1
.
When representing numbers in binary, each value is expressed as a power of two. For example, 1 is 1 * 2^0
, and 10 is 1 * 2^1 + 0 * 2^0
.
The problem arises because not all decimal numbers can be accurately represented in this binary format. Some numbers have repeating values in binary. Even though computers can approximate these decimal numbers, precision is lost during calculations since a point of truncation is necessary. Thus, the unexpected results mentioned earlier are produced.
To overcome this issue, you can utilize libraries such as decimal.js
, bignumber.js
, or big.js
. These libraries provide additional precision for decimal arithmetic.
Alternatively, you can apply a “trick” to handle the problem. One approach is to limit the number of decimal places by multiplying the numbers by a power of 10 and then dividing them after the calculation.
Here’s an example:
0.1 + 0.2 //0.30000000000000004
(0.1.toFixed(2) * 100 + 0.2.toFixed(2) * 100) / 100 //0.3
By using 10000
instead of 100
, you can maintain four decimal places.
Here’s another example with a more abstracted function:
const sum = (a, b, positions) => {
const factor = Math.pow(10, positions)
return (a.toFixed(positions) * factor + b.toFixed(positions) * factor) / factor
}
sum(0.1, 0.2, 4) //0.3
Tags: JavaScript, decimal arithmetic, programming, precision