The precision of parseFloat of method in javascript is discussed

  • 2020-03-29 23:59:48
  • OfStack

The parseFloat() method causes precision problems in Javascript
 
<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("<br/>") 
document.write("a+b+c=" + sum2) 
</script> 

The sum of a, b and c would have been 1.3921, but sum1 came up with 1.3921000000000001, which is not the desired result, especially when it comes to calculating money. Can be corrected by using the toFixed(n) method (n is the exact number of digits after the decimal).

For example: parseFloat(1.392143). ToFixed (2)=1.39.

Related articles: