JavaScript Rounding Method Rollup _javascript tips

Source: Internet
Author: User
Tags rounding plus

The functions rounded in native JavaScript are toFixed (n), and N is the number of decimal places to keep. (0<= n <=20)

Copy Code code as follows:

var num=1.0999;
Console.log (Num.tofixed (20));

http://jsfiddle.net/14x0vhu6/

The output value is not expected to be 1.0999, but 1.09990000000000009983, this needs attention, as for the reason to be perfected.

In a different browser version, if the decimal point and the previous one to intercept are 0 o'clock, there may be an irrational interception.

Copy Code code as follows:

var num=0.07;
Console.log (num.tofixed (1));

http://jsfiddle.net/ogwnw2j3/
The value may be 0.0

The approach is to add 1 before using the Tofixed method, and then subtract 1 after use.

Copy Code code as follows:

var number=0.07
var fixnum = new Number (number + 1). toFixed (1);/Before rounding plus 1
var fixednum = new Number (fixNum-1). toFixed (1);//After rounding minus 1, 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.