货币格式化:整数部分每3位用逗号分割,小数部分必须为2位,不足2位补零,多于2位四舍五入
程序员文章站
2022-07-14 23:40:49
...
<!DOCTYPE html>
<html>
<body>
<script>
var numFormat = new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
/**
* 整数部分每3位用逗号分割。
* 小数部分必须为2位,不足2位补零,多于2位四舍五入
*/
function formatCurrency(number) {
return numFormat.format(number);
}
// 测试0
console.log('0=' + formatCurrency(0));
console.log('-0=' + formatCurrency(-0));
console.log('0.0=' + formatCurrency(0.0));
console.log('-0.0=' + formatCurrency(-0.0));
// 测试1位整数
console.log('3=' + formatCurrency(3));
console.log('-3=' + formatCurrency(-3));
// 测试3位整数
console.log('123=' + formatCurrency(123));
console.log('-123=' + formatCurrency(-123));
// 测试5位整数
console.log('12345=' + formatCurrency(12345));
console.log('-12345=' + formatCurrency(-12345));
// 测试7位整数
console.log('1234567=' + formatCurrency(1234567));
console.log('-1234567=' + formatCurrency(-1234567));
// 测试1位小数
console.log('12345.3=' + formatCurrency(12345.3));
console.log('-12345.3=' + formatCurrency(-12345.3));
// 测试2位小数
console.log('12345.34=' + formatCurrency(12345.34));
console.log('-12345.34=' + formatCurrency(-12345.34));
// 测试3位小数
console.log('12345.344=' + formatCurrency(12345.344));
console.log('-12345.344=' + formatCurrency(-12345.344));
console.log('12345.345=' + formatCurrency(12345.345));
console.log('-12345.345=' + formatCurrency(-12345.345));
</script>
</body>
</html>
0=0.00
-0=-0.00
0.0=0.00
-0.0=-0.00
3=3.00
-3=-3.00
123=123.00
-123=-123.00
12345=12,345.00
-12345=-12,345.00
1234567=1,234,567.00
-1234567=-1,234,567.00
12345.3=12,345.30
-12345.3=-12,345.30
12345.34=12,345.34
-12345.34=-12,345.34
12345.344=12,345.34
-12345.344=-12,345.34
12345.345=12,345.35
-12345.345=-12,345.35
参考资料见这里