in the user’s browser and in NodeJS on the server.
In JavaScript, a number is represented in a 64-bit IEEE-754 format, i.e., it stores a floating-point value, which can lead to inaccurate calculations.
For example, the following comparison will be defined in JavaScript as false:
alert( 0.1 + 0.2 == 0.3 ); // false
This is because the value of 0.3 in JavaScript is calculated as follows:
alert( 0.1 + 0.2 ); // 0.30000000000000004
This happens because a number is stored in memory as a sequence of bitsones and zeros. Fractions in such a binary system become infinite fractions.
JavaScript does not store exact values of 0.1 or 0.2. The IEEE-754 number format rounds such fractions to the nearest possible number, for example:
alert( 0.1.toFixed(20) ); // 0.10000000000000000555
When we sum two fractions, their “inaccuracies” are also summed.
Please note, that the inaccuracy in precision for floating-point numbers is retained in any language that uses IEEE-754 format, including PHP, Java, C, Perl, and Ruby.
Solve a fractional calculus problem
You can try avoiding fractions altogether, or you can use the following methods.
- Round the result of the calculation using the
toFixed(n)
method:
let sum = 0.1 + 0.2;
alert( sum.toFixed(2) ); // 0.30
The toFixed(n)
method always returns a string, so you will get a result with the given number of digits in the decimal part.
- Temporarily multiply a number by 100 (or greater) to bring it to an integer. Then do the math and divide back by 100. Summing integers reduces the inaccuracy, but it still appears in the final division:
alert( (0.1 * 10 + 0.2 * 10) / 10 ); // 0.3
alert( (0.28 * 100 + 0.14 * 100) / 100); // 0.4200000000000001
Thus, the multiplication and division methods reduce the error but does not completely solve it.