开发者

toFixed() replacement function [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

I have noticed that many people are having trouble with the toFixed() method in javascript.

I, myself, had a website that was throwing fits in IE7 and FireFox 4.x.

I finally found the problem was the toFixed() method. It seemed to return a string in some browsers and not in others - it seems to act unpredictably.

Rather than have to do the same parseFloat/integer gymnastics every time I use this method, I decided to just extend the prototype object and create my own method.

With this method you can round to any number of decimal places AND you can specify the type of rounding to use: floor, ceil, or null to use standard rounding (round).

CODE:

     // a replacement for the toFixed() function in javascript

    Number.prototype.trimNum = function(places,rounding){

    var places,result,num = parseFloat(this),multiplier = Math.pow( 10,places );

    try {
        result = Math[rounding](num * multiplier) / multiplier;
    } catch(e){
        result = Math.round(num * multiplier) / multiplier; 
    }

    return Number( result );
} 

USAGE:

mynumbervar.trimNum(2,'floor') to round using floor

mynumbervar.trimNum(2,'ceil') to round using ceil

mynumbervar.trimNum(2) to round using round

Of course the number "2" here would be the number of decimal places to preserve.

I have tested it in IE, Safari, Chrome, and FireFox on the PC and mac and it seems to be working well f开发者_运维百科or me.

I hope this helps someone else avoid the toFixed() headaches I had....

Does anyone know of any problems with this or any suggestions to improve it?


A couple suggestions for the function:

Why declare a local variable "places" when that's a parameter passed in? You don't really need the try/catch. You could just default the rounding parameter to "round".

// a replacement for the toFixed() function in javascript

Number.prototype.trimNum = function(places, rounding) {
    rounding = rounding || "round";
    var num = parseFloat(this), multiplier = Math.pow(10, places);
    return(Number(Math[rounding](num * multiplier) / multiplier));
}

The only syntactical difference with this one is that it will fail if a bad value for rounding is passed in whereas yours would have used "round" in that case. I think it's probably better to fail if a bad operation is passed in.

Here's a working example with a bunch of test cases: http://jsfiddle.net/jfriend00/5KRBK/.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜