首页 > 其他 > 详细

toFixed

时间:2019-01-16 13:46:39      阅读:218      评论:0      收藏:0      [点我收藏+]

经典二选一

前者可以 输入 [ 4. ] 后者不行!

运行代码

console.log(toFixed(4.,2))// 1
console.log(toFixed(5.,2))// 1
                        
console.log(4.0 .toFixed(2))// 1
console.log('4.' .toFixed(2))// 1

运行结果

技术分享图片

function toFixed(number, decimal) {
    decimal = decimal || 0;
    var s = String(number);
    var decimalIndex = s.indexOf('.');
    if (decimalIndex < 0) {
        var fraction = '';
        for (var i = 0; i < decimal; i++) {
            fraction += '0';
        }
        return s + '.' + fraction;
    }
    var numDigits = s.length - 1 - decimalIndex;
    if (numDigits <= decimal) {
        var fraction = '';
        for (var i = 0; i < decimal - numDigits; i++) {
            fraction += '0';
        }
        return s + fraction;
    }
    var digits = s.split('');
    var pos = decimalIndex + decimal;
    var roundDigit = digits[pos + 1];
    if (roundDigit > 4) {
        //跳过小数点
        if (pos == decimalIndex) {
            --pos;
        }
        digits[pos] = Number(digits[pos] || 0) + 1;
        //循环进位
        while (digits[pos] == 10) {
            digits[pos] = 0;
            --pos;
            if (pos == decimalIndex) {
                --pos;
            }
            digits[pos] = Number(digits[pos] || 0) + 1;
        }
    }
    //避免包含末尾的.符号
    if (decimal == 0) {
        decimal--;
    }
    return digits.slice(0, decimalIndex + decimal + 1).join('');
}
var a = 19.02
var b = 209.01
// 结果
console.log(toFixed(a, 2)); //==> 19.02
console.log(toFixed(b, 2)); //==> 209.01
console.log(Number(toFixed(a, 2)) < Number(toFixed(b, 2))); //==> true

Number.prototype.toFixed = function (fractionDigits) {
   var num = this;
   return Math.round(num * Math.pow(10, fractionDigits)) / Math.pow(10, fractionDigits);
};
                        

toFixed

原文:https://www.cnblogs.com/userzf/p/10276527.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!