Inaccurate calculations in JavaScript

Fractions are stored in computers in such a way that they can often be inaccurately represented. In this case, some surprise can wait you when a routine operation produces a strange result. The example:

let a = 0.1 + 0.2; alert(a); // shows 0.30000000000000004

To prevent this behavior, you can use the special method toFixed, which rounds up to a given position in the fractional part. Let's round up our result:

let a = 0.1 + 0.2; alert(a.toFixed(2)); // shows '0.30'

The toFixed method returns the result as a string. You can convert its result to a number:

let a = 0.1 + 0.2; alert(+a.toFixed(2)); // shows 0.3

Check the result of the next operation:

alert(0.1 * 0.2);

Check the result of the next operation:

alert(0.3 - 0.1);
enru