The realization code _javascript skill of JS control decimal digit number

Source: Internet
Author: User
Tags reserved
Yesterday, when using JS to the foreground floating-point number to find that:
0.05+1.08=1.1300000000000001
Check on the Internet there is indeed such a bug, in addition to the number of digits on the control there is no good way (hope that experts can put forward
Other ideas).
So I write a control of the decimal number of the JS method to solve the development of the immediate
Copy Code code as follows:

Decimal digit control, can be rounded
function fractional (n) {
Number of decimal reserved digits
var bit = 2;
Add a decimal point to expand the 1-bit
bit++;
Number to String
n = n.tostring ();
Get decimal point position
var point = N.indexof ('. ');
The length of n is greater than the length of the reserved digits
if (N.length > point + Bit) {
The number of decimal digits is greater than 4, 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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.