zoukankan      html  css  js  c++  java
  • 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;
    };

    转载--

  • 相关阅读:
    SqlServer 格式化时间
    工作生活两三事
    前端面试题准备 3
    前端面试题准备 2
    MYSQL---自定义函数
    MYSQL---MD5()、PASSWORD()函数
    MYSQL---DATE_ADD()
    MYSQL---%
    MYSQL---多表删除
    MYSQL---CREATE...SELECT
  • 原文地址:https://www.cnblogs.com/Mousika/p/7197741.html
Copyright © 2011-2022 走看看