JS Processing rounding function toFixed (n) (preferably n digits after decimal point)

Source: Internet
Author: User

The function that is rounded in JS is toFixed (n), and N is the number of decimal digits to keep. N is 0~20, and when N exceeds 20, JS will go wrong.

If it is 0 o'clock before the decimal point and the previous one to be intercepted, it is not normally intercepted.
var h=0.07
The value of h.tofixed (1) is 0.0


In fact, to solve this problem, it is not necessary to rewrite JS in the number type of the Tofixed method.
A very cow colleague, think of a he said very stupid, but I feel very cow method.
The JS API says that at least one of the intercepted bits is not 0.
So, his stupid but very good way is: Use the tofixed method before adding 1, after use and then minus 1.

1     var num = 0.007;//The number  to be rounded 2    var fixnum = new (num+1). toFixed (2);//+ 1 before rounding   3     var fixednum = new Number (fixNum-1). toFixed (2);//minus 1 after rounding, then rounding   4     alert ( Fixednum);//The number that pops up is the correct rounding result.  

Method Two:

The following script overrides the tofixed () so that 0.056 can be converted to 0.1.

1 number.prototype.tofixed=function (len)2 {3 var add = 0;4 var s,temp;5 var S1 = this + "";6 var start = S1.indexof (".");7 if (s1.substr (start+len+1,1) >=5) add=1;8 var temp = Math.pow (10,len);9 s = Math.floor (This * temp) + add;Ten return s/temp; One}

Article from: http://blog.csdn.net/nuptsv_ice/article/details/10493659

JS Processing rounding function toFixed (n) (preferably n digits after decimal point)

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.