js金额格式化(逗号隔开,保留2位小数)

本文介绍了一个JavaScript函数,用于将数字转换成带有千分位分隔符的格式,并且可以指定保留的小数位数。该函数考虑了不同数字类型的情况,并通过四舍五入确保结果的准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

举例
转换前:123456789.87654321
转换后:123,456,789.88

// 金额格式化
        const moneyFormat = (num, decimal = 2, split = ',') => {
            /*
                parameter:
                num:格式化目标数字
                decimal:保留几位小数,默认2位
                split:千分位分隔符,默认为,
                moneyFormat(123456789.87654321, 2, ',') // 123,456,789.88
            */
            function thousandFormat (num) {
                const len = num.length
                return len <= 3 ? num : thousandFormat(num.substr(0, len - 3)) + split + num.substr(len - 3, 3)
            }
            if (isFinite(num)) { // num是数字
                if (num === 0) { // 为0
                return num.toFixed(decimal)
                } else { // 非0
                var res = ''
                var dotIndex = String(num).indexOf('.')
                if (dotIndex === -1) { // 整数
                    res = thousandFormat(String(num)) + '.' + '0'.repeat(decimal)
                } else { // 非整数
                    // js四舍五入 Math.round():正数时4舍5入,负数时5舍6入
                    // Math.round(1.5) = 2
                    // Math.round(-1.5) = -1
                    // Math.round(-1.6) = -2
                    // 保留decimals位小数
                    const numStr = String((Math.round(num * Math.pow(10, decimal)) / Math.pow(10, decimal)).toFixed(decimal)) // 四舍五入,然后固定保留2位小数
                    const decimals = numStr.slice(dotIndex, dotIndex + decimal + 1) // 截取小数位
                    res = thousandFormat(numStr.slice(0, dotIndex)) + decimals
                }
                return res
                }
            } else {
                return '--'
            }
        }
        console.log('result:', moneyFormat(123456789.87654321)) // '123,456,789.88'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值