Javascript calculation error?
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:
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..