Sogrey / Web-QA

https://sogrey.github.io/Web-QA/
MIT License
6 stars 2 forks source link

如何优雅的实现金钱格式化:1234567890 --> 1,234,567,890 #304

Open Sogrey opened 4 years ago

Sogrey commented 4 years ago

用正则魔法实现:

var test1 = '1234567890'
var format = test1.replace(/\B(?=(\d{3})+(?!\d))/g, ',')

console.log(format) // 1,234,567,890

非正则的优雅实现:

 function formatCash(str) {
 return str.split('').reverse().reduce((prev, next, index) => {
 return ((index % 3) ? next : (next + ',')) + prev
 })
}
console.log(formatCash('1234567890')) // 1,234,567,890