前言
格式化金额,例如把数字 98765432 格式化为:¥987,654.32。¥符号可以换成别的,也可以去掉
const formatStatistic = (text, precision = 2, divPrecision = true, icon = '¥') => {
//precision是保留小数位数,divPrecision 是否需要除以精度(也就是在原来的基础上除以精度)
if (text === undefined || text === null || text === "" || isNaN(text)) {
return "-";
}
let mulNum = 1;
if (divPrecision && precision) {
for (let i = 1; i <= precision; i++) {
mulNum = mulNum * 10
}
}
let value = (text / mulNum)
if (precision) {
value = value.toFixed(precision)
}
value = value && value.toString()
.replace(/(^|\s)\d+/g, (m) => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
if (icon) {
value = icon + value;
}
return value
}
let result = formatStatistic(98765432);
console.log('result----', result); // ¥987,654.32
formatStatistic(98765432, 3); // ¥98,765.432
formatStatistic(98765432, 2, false); // ¥98,765,432.00