Javascript rounding method summary, javascript rounding

Source: Internet
Author: User

Javascript rounding method summary, javascript rounding

The rounding function toFixed (n) in native javascript, where n is the number of decimal places to be retained. (0 <= n <= 20)

Copy codeThe Code is as follows:
Var num = 1.0999;
Console. log (num. toFixed (20 ));

Http://jsfiddle.net/14x0vhu6/

The output value is not the expected 1.0999, but 1.09990000000000009983. You need to pay attention to this. The reasons are to be improved.

In addition, in different browser versions, if the first digit before the decimal point and the first digit to be truncated are both 0, it may be unreasonable to intercept.

Copy codeThe Code is as follows:
Var num = 0.07;
Console. log (num. toFixed (1 ));

Http://jsfiddle.net/ogwnw2j3/
The value may be 0.0
 
The solution is to add 1 before using the toFixed method, and then subtract 1 after using it.

Copy codeThe Code is as follows:
Var numbers = 0.07
Var fixNum = new Number (number + 1). toFixed (1); // Add 1 before rounding
Var fixedNum = new Number (fixNum-1). toFixed (1); // deduct 1 after rounding and then rounding
Console. log (fixedNum );

Http://jsfiddle.net/euvn0L1g/

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.