首页 > Web开发 > 详细

JS toFixed四舍五入精度校正

时间:2019-11-13 16:54:18      阅读:95      评论:0      收藏:0      [点我收藏+]
var a = 2.255;
var b = a.toFixed(2);
console.log(b);

以上代码,按预期正常四舍五入得到结果应该是2.26,但实际返回值为2.25

js浮点数精度作为前端必踩坑,谁也逃不过,不过我们可以改写原型上的方法达到目的

Number.prototype.toFixed = function (n) {
    if (n > 20 || n < 0) {
        throw new RangeError(‘toFixed() digits argument must be between 0 and 20‘);
    }
    const number = this;
    if (isNaN(number) || number >= Math.pow(10, 21)) {
        return number.toString();
    }
    if (typeof (n) == ‘undefined‘ || n == 0) {
        return (Math.round(number)).toString();
    }

    let result = number.toString();
    const arr = result.split(‘.‘);

    // 整数的情况
    if (arr.length < 2) {
        result += ‘.‘;
        for (let i = 0; i < n; i += 1) {
            result += ‘0‘;
        }
        return result;
    }

    const integer = arr[0];
    const decimal = arr[1];
    if (decimal.length == n) {
        return result;
    }
    if (decimal.length < n) {
        for (let i = 0; i < n - decimal.length; i += 1) {
            result += ‘0‘;
        }
        return result;
    }
    result = integer + ‘.‘ + decimal.substr(0, n);
    const last = decimal.substr(n, 1);

    // 四舍五入,转换为整数再处理,避免浮点数精度的损失
    if (parseInt(last, 10) >= 5) {
        const x = Math.pow(10, n);
        result = (Math.round((parseFloat(result) * x)) + 1) / x;
        result = result.toFixed(n);
    }

    return result;
};

原文地址:http://www.jianshu.com/p/849b0ae36b36

JS toFixed四舍五入精度校正

原文:https://www.cnblogs.com/liangtao999/p/11850570.html

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