JavaScript code for controlling decimal places

Source: Internet
Author: User

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

Related Article

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.