• 四舍五入toFoxed方法


    四舍五入的方法:

    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;
        };

    核心方法:

    function tofixed(num,n){
        let result = num.toString();
        const arr = result.split('.');
        const integer = arr[0];
        const decimal = arr[1];
        if (decimal.length == n) { //小数位等于要求长度,无需处理
            return result;
        }
        if (decimal.length < n) {
            result = integer + '.' + decimal.padEnd(2,'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); //10的n次方
            result = (Math.round((parseFloat(result) * x)) + 1) / x;
            result = result.toFixed(n);
        }
    
        return result;
    }
    
    let handleNum = tofixed(10.234,2);
    console.log(handleNum); //10.23
    let handleNum2 = tofixed(10.235,2);
    console.log(handleNum2); //10.24
    let handleNum3 = tofixed(10.5,2);
    console.log(handleNum3); //10.50
  • 相关阅读:
    页面加载完毕相关信息淡入效果
    导航菜单底部滑动条跟随效果
    我要成为优秀的前端一员!
    (转)git合并多个commit
    Windows 7 + PHP 5.3 + WAMP 下 Imagick 扩展安装
    使用 PHP 框架 Yii 访问 MS SQL 的尝试
    拼合逐月数据系列
    编程视频教程推荐
    Java 实现 Domino邮箱自动注册
    二、 编写一个类,用两个栈实现队列,支持队列的基本操作(add,poll,peek)
  • 原文地址:https://www.cnblogs.com/xiaozhumaopao/p/11446994.html
Copyright © 2020-2023  润新知