Home > Web Front-end > JS Tutorial > Discussion on the accuracy of parseFloat() method in javascript_javascript skills

Discussion on the accuracy of parseFloat() method in javascript_javascript skills

WBOY
Release: 2016-05-16 17:12:16
Original
1061 people have browsed it

The parseFloat() method in Javascript will cause accuracy problems

Copy code The code is as follows:

< ;script language="javascript">
var a = "0.11";
var b = "0.2801";
var c = "1.002";
var sum1 = parseFloat(a) parseFloat (b) parseFloat(c);
var sum2 = (parseFloat(a) parseFloat(b) parseFloat(c)).toFixed(4)
document.write("a b c=" sum1);
document.write("
")
document.write("a b c=" sum2)


A, b, c are added together It was originally 1.3921, but the result obtained by sum1 is: 1.3921000000000001. This is not the desired result, especially when calculating money, such precision is not required. You can use the toFixed(n) method to correct it (n is the precise number of digits after the decimal).

For example: parseFloat(1.392143).toFixed(2)=1.39.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template