-
Notifications
You must be signed in to change notification settings - Fork 6
Open
Description
题目:
请实现一个按千分位格式化金额数值的功能
function formatMoney(num) {
// 你的代码
}测试用例:
formatMoney(100); // 100.00
formatMoney(1000); // 1,000.00
formatMoney(1000.56); // 1,000.56
formatMoney(1000000000.25); // 1,000,000,000.25参考答案:
function formatMoney(num) {
// 字符串捕获(零宽度正预测先行断言)
let regex = /\d{1,3}(?=(\d{3})+$)/g;
// 将字符串拆分成“符号”(如有)、“整数位”和“小数位”三部分
return String(num).replace(/^(-|\+?)(\d+)((\.\d+)?)$/, (s, s1, s2, s3) => (
// $&表示 replace() 函数第一个正则表达式参数所匹配的内容
s1 + s2.replace(regex, '$&,') + s3
));
}相关资料:正则表达式零宽断言
MuaCoding
Metadata
Metadata
Assignees
Labels
No labels