The unification of the accuracy of the rewriting of JS toFixed () method

Source: Internet
Author: User
Tags pow tostring

  Anyone who has used the Tofix () method in JS, should know that this method has a small bug, under IE and FF for decimal carry a little different

Whenever you have used the Tofix () method in JS, you should know that there is a small bug in this method.   under IE and FF are a little different for decimal numbers.   For example (0.005) Tofix (2) =0.00 under IE. Under FF Tofix (2) =0.01.  This can result in data differences.   We can rewrite this method to achieve the unity of precision.     Code is as follows: Number.prototype.toFixed = function (s)   {  return (parseint (this * MATH.POW (s) + 0.5)/ Math.pow (s)). ToString (); }    But doing so still has a problem in all browsers, String ("0.050"). Tofix (2) =0.1  We can see that you're going to have to keep two decimal places and become one. Other words. This rewrite only tofixed () will automatically discard the final 0.  we need to do further processing of this method.     Code as follows: Number.prototype.toFixed = function (s)   {  changenum= (parseint (This * MATH.POW (s) + 0.5 )/Math.pow (s)). ToString ();  index=changenum.indexof (".");   if (index<0&&s>0) {  changenum=changenum+ ".";   for (i=0;i<s;i++) {  changenum=changenum+ "0"; }   }else {  index= changenum.length-index;  for (i=0;i< (s-index) +1;i++) {  changenum=changenum+ "0"; }   }     Return changenum;&nbsp }   

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.