项目中使用 toFixed 出现的问题:

一. js报错 Uncaught SyntaxError: Invalid or unexpected token

如下图所示:

就是说对 整数 和 字符串 使用toFixed() 会报错

问题一其实是toFixed的使用问题

x.toFixed(n) 方法可把 Number类型的数字x 四舍五入为指定小数位数的数字, n为保留的小数位数,并且返回的结果是字符串类型

注意这里x 必须为数字Number类型,如果用字符串的话报错

3.toFixed(2) 也会报错,原因是js引擎在运行的时候,默认将3后面的那个点认为是小数点,所以3.toFixed()也就相当于3.0toFixed(), 所以报错

解决方法如下:

  1. 多加一个点: 3..toFixed(2) // 输出 3.00
  2. 把数字存一个变量上
  3. let num = 3
    num.toFixed(2) // 输出 3.00
    
  4. 用括号: (3).toFixed(2) // 输出 3.00

浏览器的toFixed() 存在的问题如下:

  1. 四舍五入不准确,并且在不同浏览器下也存在差异
  2. 有时会出现小数的精度特别长的情况,当然这个的本质其实是小数的精度问题

对于以上的问题,可以把toFixed() 方法重写了, 也可以使用别人的轮子,比如: bignumber

==================================================================

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>

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐