Home > Web Front-end > JS Tutorial > JS implementation code to control the number of decimal places_javascript skills

JS implementation code to control the number of decimal places_javascript skills

WBOY
Release: 2016-05-16 18:04:06
Original
1174 people have browsed it

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

Copy the code The code is as follows:

//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;
}
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