Yesterday, when I used JS to calculate the front-end floating point numbers, I found:
0.05 1.08=1.1300000000000001
I checked online that this kind of bug does exist, and there is no good method except controlling the number of digits (I hope experts can Suggest
other ideas).
So I wrote a JS method to control the number of decimal places to solve the urgent need of development
//Decimal number control, can be rounded
function Fractional(n) {
//The number of decimal places to retain
var bit = 2;
//After adding the decimal point To extend 1 digit
bit;
//Convert number to string
n = n.toString();
//Get the decimal point position
var point = n.indexOf('. ');
//The length of n is greater than the length of reserved digits
if (n.length > point bit) {
//Whether the reserved decimal digit is greater than 4, greater than 4 carry
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;
}
Statement: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