一.使用字符串操作方法格式化
①整数金额格式化:
function moneyFormat (num) { const len = num.length return len <= 3 ? num : this.moneyFormat(num.slice(0, len - 3)) + ',' + num.slice(len - 3, len) } var num = var res = moneyFormat(String(num)) console.log('result:', res) // '12,345,000'
讯享网
②自定义保留decimal位小数,并使用split分隔符的数字格式化:
讯享网function moneyFormat (num, decimal = 2, split = ',') { /* parameter: num:格式化目标数字 decimal:保留几位小数,默认2位 split:千分位分隔符,默认为, moneyFormat(., 2, ',') // 123,456,789.88 */ function thousandFormat (num) { const len = num.length return len <= 3 ? num : thousandFormat(num.slice(0, len - 3)) + split + num.slice(len - 3, len) } if (isFinite(num)) { // num是数字 if (num === 0) { // 为0 return num.toFixed(decimal) } else { // 非0 var res = '' var dotIndex = String(num).indexOf('.') if (dotIndex === -1) { // 整数 if (decimal === 0) { res = thousandFormat(String(num)) } else { 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(.)) // '123,456,789.88'
二.使用正则表达式格式化
①整数金额格式化:
function moneyFormat (num) { return String(num).replace(/(\d)(?=(?:\d{3})+$)/g, '$1,') } var num = var res = moneyFormat(num) console.log('result:', res) // '12,345,000'
②自定义保留decimal位小数,并使用split分隔符的数字格式化:
讯享网function moneyFormat (num, decimal = 2, split = ',') { /* parameter: num:格式化目标数字 decimal:保留几位小数,默认2位 split:千分位分隔符,默认为, moneyFormat(., 2, ',') // 123,456,789.88 */ if (isFinite(num)) { // num是数字 if (num === 0) { // 为0 return num.toFixed(decimal) } else { // 非0 var res = '' var dotIndex = String(num).indexOf('.') if (dotIndex === -1) { // 整数 if (decimal === 0) { res = String(num).replace(/(\d)(?=(?:\d{3})+$)/g, `$1${split}`) } else { res = String(num).replace(/(\d)(?=(?:\d{3})+$)/g, `$1${split}`) + '.' + '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 = String(numStr.slice(0, dotIndex)).replace(/(\d)(?=(?:\d{3})+$)/g, `$1${split}`) + decimals } return res } } else { return '--' } } console.log('result:', moneyFormat(.)) // '123,456,789.88'

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/61616.html