码迷,mamicode.com
首页 > Web开发 > 详细

js实现toFixed截取效果

时间:2017-07-17 23:51:25      阅读:333      评论:0      收藏:0      [点我收藏+]

标签:ssi   present   number   log   ==   which   rac   substring   prototype   

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截取效果

标签:ssi   present   number   log   ==   which   rac   substring   prototype   

原文地址:http://www.cnblogs.com/Mousika/p/7197741.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!