How to solve the problem of parseFloat accuracy in js
This article mainly introduces "how to solve the problem of parseFloat accuracy in js". In daily operation, I believe many people have doubts about how to solve the problem of parseFloat accuracy in js. Xiaobian consulted all kinds of data and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubt of "how to solve the problem of parseFloat accuracy in js". Next, please follow the editor to study!
When calculating the amount in yuan in js, the use of parseFloat will cause precision problems.
What is the problem of float accuracy?
Varprice=10.99
Varquantity=7
VarneedPay=parseFloat (price*quantity)
The correct result of needPay should be 76.93 yuan, but after running, it is found that the needPay is 76.930000000001.
This situation can be corrected by the toFixed (n) method, but this method requires a higher version of js and is not compatible with ie5.
Float precision solution
The amount in yuan is multiplied by 100 into points.
Varprice=10.99
Varquantity=7
VarneedPay=Math.floor (parseFloat (price*100*quantity)) / 100
The calculated result of parseFloat (price*100*quantity) is 7693.0000000001 rounded by the Math.round () method, and divided by 100 is the correct result.
PS: one thing I learned by the way: the difference between Math.ceil () Math.floor () Math.round ()
Math.ceil () is rounded up
Math.floor () is rounded down
Math.round () is rounded
Copy the code
/ / keep two decimal places
/ / function: round the floating point to 2 decimal places
FunctiontoDecimal (x) {
Varf=parseFloat (x)
If (isNaN (f)) {
Return
}
F=Math.round (xylene 100) / 100
Returnf
}
At this point, the study on "how to solve the problem of parseFloat accuracy in js" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!