When I used JS to calculate the floating point number at the front end yesterday, I found that:
0.05 + 1.08 = 1.1300000000000001
This kind of Bug exists when I check the internet, and there is no good method besides the number of digits (I hope the experts can propose
Other ideas ).
As a result, I wrote a JS method to control the number of decimal places to solve the urgent need for development.
Copy codeThe Code is as follows:
// Controls the number of decimal places, which can be rounded down.
Function Fractional (n ){
// Decimal reserved digits
Var bit = 2;
// Add one decimal point
Bit ++;
// Convert digits into strings
N = n. toString ();
// Obtain the decimal point
Var point = n. indexOf ('.');
// The length of n is greater than the length of the reserved digits.
If (n. length> point + bit ){
// Whether the last decimal digit is greater than 4 and greater than 4.
If (parseInt (n. substring (point + bit, point + bit + 1)> 4 ){
Return n. substring (0, point) + "." + (parseInt (n. substring (point + 1, point + bit) + 1 );
}
Else {
Return n. substring (0, point) + n. substring (point, point + bit );
}
}
Return n;
}