1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > js金额格式化(逗号隔开 保留2位小数)

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

时间:2024-04-11 20:03:38

相关推荐

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

举例

转换前: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.lengthreturn len <= 3 ? num : thousandFormat(num.substr(0, len - 3)) + split + num.substr(len - 3, 3)}if (isFinite(num)) {// num是数字if (num === 0) {// 为0return num.toFixed(decimal)} else {// 非0var 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'

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。