zoukankan      html  css  js  c++  java
  • toFixed()四舍五入的不准确性

    chrome下的测试结果:

    修正方案:

        <script>
            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);
                    console.log(x, parseFloat(result))
                    result = (Math.round((parseFloat(result) * x)) + 1) / x;
                    result = result.toFixed(n);
                }
                return result;
            }
        </script>
    
  • 相关阅读:
    Unity Shader 之 渲染流水线
    C# 如何快速取到enum中的枚举数量
    Unity NGUI ScrollView 苹果式滑动
    多元线性回归~ML
    梯度下降~ML
    代价函数~ML
    ML~线性代数~python
    unity 大游戏使用什么框架
    C# Activator.CreateInstance()方法使用
    VSync Count 垂直同步
  • 原文地址:https://www.cnblogs.com/chyshy/p/14745284.html
Copyright © 2011-2022 走看看