JS如何实现价格计算(关键词-3.10)

JS如何实现价格计算?结果保留两位小数
比如:3.156变为3.16
3.1422变为3.15
3.10仍是3.10

四舍五入用toFixed转下就行,参数为要保留的小数位。不过看题主要求是舍入后面的位数不是0就直接进位可以先乘Math.pow(10,2),在调用Math.ceiling得到进位后再除以Math.pow(10,2),在toFixed转即可
示例代码如下


    function toFixed(num, decimalNum = 2) {
        num = Math.ceil(num * Math.pow(10, decimalNum));
        num /= Math.pow(10, decimalNum);        
        return num.toFixed(decimalNum )
    }
    console.log(toFixed(3.156))
    console.log(toFixed(3.1422))
    console.log(toFixed(3.10))

            四舍五入保留2位小数(不够位数,则用0替补)  
            function keepTwoDecimalFull(num) {
                var result = parseFloat(num);
                if (isNaN(result)) {
                    alert('传递参数错误,请检查!');
                    return false;
                }
                result = Math.round(num * 100) / 100;
                var s_x = result.toString(); //将数字转换为字符串
                var pos_decimal = s_x.indexOf('.'); //小数点的索引值
                // 当整数时,pos_decimal=-1 自动补0  
                if (pos_decimal < 0) {
                    pos_decimal = s_x.length;
                    s_x += '.';
                }
                // 当数字的长度< 小数点索引+2时,补0  
                while (s_x.length <= pos_decimal + 2) {
                    s_x += '0';
                }
                return s_x;
            }
            console.log(keepTwoDecimalFull(120.5)); //120.50
            console.log(typeof keepTwoDecimalFull(120.5)); //string
            console.log(keepTwoDecimalFull(2.446242342)); //2.45
            console.log(typeof keepTwoDecimalFull(2.446242342)); //string

img


https://blog.csdn.net/weixin_48674314/article/details/122623165

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632