The problem of floating point accuracy, why 0.1mm 0.15mm 0.1 = 5.1?

in js, we often encounter the problem of floating-point precision (0.1-0.2). We all know that it is because infinite cyclic decimals are generated when converting to binary, while the Mantissa part of js can only hold 52 digits, which is caused by intercepting a zero. But now dig deep:

,

const s = 0.1
console.log(s)//s=0.1    

console.log(0.1+5)//5.1

,

the above code, s is exactly equal to 0.1, and there is no inaccuracy. According to the data, more than 16 bits will be calculated using toPrecision (16), and then there will be the case of slicing 0.1, so why can"t 0.1 / 0.2 do the toPrecision operation?

for the second case, my guess is that for the addition of integers and decimals, js will do toPrecision (m = 1), m is the-m power of decimal 10;
these are the two problems I have in studying the accuracy of js, and the blogs that can be found do not explain these two aspects. I hope to know the great god of js precision processing mechanism to help answer, thank you!

add: for when the toPrecision (m) method is called, more importantly, how is the value of m determined?

Apr.16,2022

The mathematical operations of

JS are all floating-point operations based on the IEEE754 standard. Even 5x 0.1 is floating-point number 5 + floating-point number 0.1 .
the cause of the error is that the error caused by taking a zero cannot be simply ignored.

5x0.1 = 5.1 or other similar mathematical operation holds because the floating-point numbers of the results on both sides are really equal (symbol bits, orders, Mantissa are all the same, or slightly different, but the precision is the same after processing, but I'm not sure).


JS2.3.2 :

0.1+0.2 === 0.3 //false

from a mathematical point of view, the above condition should be true, but why the result is false?
to put it simply, 0.1 and 0.2 in binary floating point numbers are not very accurate, and the result of their sum is not exactly equal to 0.3, but a relatively close number 0.300000000000004, so the conditional result is false. If you are interested, you can check out "you don't know JS"

.
Menu