Skip to content Skip to sidebar Skip to footer

How To Write A Prototype For Number.tofixed In Javascript?

I need to round decimal numbers to six places using JavaScript, but I need to consider legacy browsers so I can't rely on Number.toFixed The big catch with toExponential, toFixed

Solution 1:

Try this:

if (!Number.prototype.toFixed)

    Number.prototype.toFixed = function(precision) {
        var power = Math.pow(10, precision || 0);
        returnString(Math.round(this * power)/power);
    }

Solution 2:

I think Firefox 1.5 and IE 5 are pretty much no longer used, or by a very minor quantity of people. It is a bit like coding to support Netscape Navigator... :-) Unless some other major browser (Opera? Safari? unlikely...) doesn't support this, or if your Web logs show lot of legacy browser use, you can probably just use these methods. Sometime, we have to move on. ^_^

[EDIT] Works fine on Opera 9.50 and Safari 3.1

javascript: var num = 3.1415926535897932384; alert(num.toFixed(7));

The article you reference is a year and half ago, an eternity in IT industry... I think that, unlike IE users, Firefox users often go to the latest version.

Solution 3:

From Bytes website, this function is almost the same than Serge llinsky's:

if (!num.toFixed) 
{
  Number.prototype.toFixed = function(precision) 
  {
     var num = (Math.round(this*Math.pow(10,precision))).toString();
     return num.substring(0,num.length-precision) + "." + 
            num.substring(num.length-precision, num.length);
  }
}

Solution 4:

Another option is ( which doesn't convert to a string unnecessarily, and also corrects the miscalculation of (162.295).toFixed(2) to 162.29 ( should be 162.30 )).

Number.prototype._toFixed=Number.prototype.toFixed; //Preserves the current functionNumber.prototype.toFixed=function(precision){
/* step 1 */var a=this, pre=Math.pow(10,precision||0);
/* step 2 */ a*=pre; //currently number is 162295.499999/* step 3 */ a = a._toFixed(2); //sets 2 more digits of precision creating 16230.00/* step 4 */ a = Math.round(a);
/* step 5 */ a/=pre;
/* step 6 */return a._toFixed(precision);
}
/*This last step corrects the number of digits from 162.3 ( which is what we get in step 5 to the corrected 162.30. Without it we would get 162.3 */

Edit: Upon trying this specific incarnation, this*=Math.pow(10, precision||0) creates an error invalid left-hand assignment. So gave the this keyword the variable a. It would also help if I closed my functions ^_^;;

Solution 5:

Try this:

Number.prototype.toFixed = function(precision) {
     var power = Math.pow(10, precision || 0);
     returnString(Math.round(this * power)/power);
 }

Post a Comment for "How To Write A Prototype For Number.tofixed In Javascript?"