// 测试数据如下:
// formatMoney(12.035); // 12.04 正常四舍五入
// formatMoney(12.045); // 12.04 异常,应该为12.05,没有四舍五入
// 解决如下
const formatMoney1 = (money, symbol = "", decimals = 2) => {
let float = (
Math.round((parseFloat(money) + Number.EPSILON) * Math.pow(10, decimals)) /
Math.pow(10, decimals)
).toFixed(decimals);
return `${symbol} ${float}`;
};
const method1 = formatMoney1(12.045)
console.log(method1)
/**
* @params {Number} money 金额
* @params {Number} decimals 保留小数点后位数
* @params {String} symbol 前置符号
*/
const formatMoney2 = (money, symbol = "", decimals = 2) => {
let result = money
.toFixed(decimals)
.replace(/\B(?=(\d{3})+\b)/g, ",")
.replace(/^/, `${symbol}$ `);
return result;
};
const method2 = formatMoney2(12.045, "$", 2); // $ 12,341,234.25
console.log(method2)
// 方式三:循环字符串,通过 slice 截取实现
// substring(start, end):包含 start,不包含 end
// substr(start, length):包含 start,长度为 length
// slice(start, end):可操作数组和字符串;包含 start,不包含 end
// splice(start, length, items):只能针对数组;增删改都可以
const formatMoney3 = (money, symbol = "", decimals = 2) => {
let arr = money.toFixed(decimals).toString().split(".");
let num = arr[0];
let first = "";
while (num.length > 3) {
first = "," + num.slice(-3) + first;
num = num.slice(0, num.length - 3);
}
if (num) {
first = num + first;
}
return `${symbol} ${[first, arr[1]].join(".")}`;
};
const method3 = formatMoney3(12341234.045, "$", 2); // $ 12,341,234.25
console.log(method3)
// 链接:https://juejin.cn/post/7028086399601475591
// 方法4
let num= 12.046
console.log( num.toLocaleString("en-US") )
console.log((12341234.045).toFixed(2).toLocaleString())
console