Why ar...">

Javascript calculation error?

Take a look at this example.

<html>
 <body onload="alert((0.1234*300));alert((0.00005*300))"/>
</html>

Why are the results not as they should be 37.02 and 0.015, but 37.019999999999996 and 0.015000000000000001?

Ps: 0.00005 * 300 make a mistake, and 0.0005 * 30 and 0.005 * 3 are ok.

+3
source share
3 answers

All JavaScript numbers are presented in binary format as IEEE-754 Doubles , which provides an accuracy of approximately 14 or 15 significant digits. Since they are floating point numbers , they do not always represent exact numbers ( Source ):

console.log(0.1234 * 300);    // 37.019999999999996
console.log(0.00005 * 300);   // 0.015000000000000001     

You will also be interested to know the following message:

+6
source

+9

Number, toString(radix) String. . toPrecision(precision), toFixed(digits) toExponential(fractionDigits). Numbers Strings, toString .

, , , ( String) .

0.1234 - . , (1234/10000). . 0.000, 500 .

,

1.1111100101110010010001110100010100111000111011110011010011010110101.. * 2^-4

1.1111100101110010010001110100010100111000111011110011 * 2^-4

IEEE754.

4.1966 * 10 ^ -18, 0.1234 0.123399999999999995803..

JavaScript, . 0.123400000.. 0,1234. - 0.1234, .

300, 37.019999999999998741.. :

1.00101000001010001111010111000010100011110101110000100110001 * 2^5

But this number must also be rounded to fit into double:

1.0010100000101000111101011100001010001111010111000010 * 2^5

This is actually 37.019999999999996021 .. but again you convert it to a string, so it is rounded to 37.019999999999996.

If you just look at the numbers 0.1234 and 0.1234 * 300, you will notice that both numbers are rounded to 17 digits:

12339999999999999580..
37019999999999996021..
+2
source

Source: https://habr.com/ru/post/1767731/


All Articles