Recently when the project encountered a more tangled JS floating point calculation problem.
At that time the interest rate calculation, because the interest rate mostly involves the decimal point, the precision request is also very high.
0.6+0.1+0.1=?
Results appear: 0.7999999999999
Online look up, this is really a flaw (Bug)
In addition, similar situations occur as long as the floating-point calculation is involved in subtraction
First Look at the demo:
Test 0.1~10, plus 0.1+0.1
1$(function () {2 varContent = "";3 for(vari = 0.1; I <= 10; i + = 0.1) {4 varresult = i + 0.1 + 0.1;5Content = content + result + ' \ t ';6 }7 alert (content);8});
Operation Result:
Workaround:
According to the tofixed method, we modify a Toround method to precisely round the decimal point:
1Number.prototype.toRound =function(d)2 {3 vars= This+"";if(!d) D=0;4 if(S.indexof (".") ==-1) s+= "."; s+=NewArray (d+1). Join ("0");5 if(NewRegExp ("^ (-|\\+)?" ( \\d+ (\\.\\d{0, "+ (d+1) +"})?) \\d*$ "). Test (s))6 {7 vars= "0" + regexp.$2, pm=regexp.$1, A=regexp.$3.length, b=true;8 if(a==d+2) {A=s.match (/\d/g);if(parseint (a[a.length-1]) >4)9 {Ten for(varI=a.length-2; i>=0; i--) {A[i] = parseint (A[i]) +1; One if(a[i]==10) {a[i]=0; b=i!=1;}Else Break;} A } -S=a.join (""). Replace (NewRegExp ("(\\d+) (\\d{" +d+ "}) \\d$"), "$1.$2"); -}if(b) S=s.substr (1);return(pm+s). Replace (/\.$/, "");}return This+""; the};
To change the method in the demo, call the Toround method:
var result = (i+0.1+0.1). Toround (2);
Results:
JS floating point calculation bug