首页 > 代码库 > js实现toFixed截取效果

js实现toFixed截取效果

Number.prototype.toFixed = function(fractionDigits) {
    var f = parseInt(fractionDigits) || 0;
    if( f < -20 || f > 100 ) { 
        throw new RangeError("Precision of " + f + " fractional digits is out of range");
    }
    var x = Number(this);
    if( isNaN(x) ) {
        return "NaN";
    }
    var s = "";
    if(x <= 0) {
        s = "-";
        x = -x;
    }
    if( x >= Math.pow(10, 21) ) {
        return s + x.toString();
    }
    var m;
// 10. Let n be an integer for which the exact mathematical value of 
// n ÷ 10^f - x is as close to zero as possible. 
// If there are two such n, pick the larger n.
    n = Math.round(x * Math.pow(10, f) );

    if( n == 0 ) {
        m = "0";
    }
    else {
        // let m be the string consisting of the digits of the decimal representation of n (in order, with no leading zeroes).
        m =  n.toString();
    }
    if( f == 0 ) {
        return s + m;
    }
    var k = m.length;
    if(k <= f) {
        var z = Math.pow(10, f+1-k).toString().substring(1);
        m = z + m;
        k = f+1;
    }
    if(f > 0) {
        var a = m.substring(0, k-f);
        var b = m.substring(k-f);
        m = a + "." + b;
    }
    return s + m;
};

转载--

js实现toFixed截取效果