钱数字格式化
2022-11-10 本文已影响0人
萘小蒽
function outputdollars (number=0) {
var numberStr = number.toString();
if (numberStr.length <= 3) return numberStr == '' ? '0' : numberStr
else {
var mod = numberStr.length % 3
var output = mod == 0 ? '' : numberStr.substring(0, mod)
for (var i = 0; i < Math.floor(numberStr.length / 3); i++) {
if (mod == 0 && i == 0) output += numberStr.substring(mod + 3 * i, mod + 3 * i + 3)
else output += ',' + numberStr.substring(mod + 3 * i, mod + 3 * i + 3)
}
return output
}
}
outputdollars(100000000)
简版
function outputdollars (num) {
let arr = []
String(num).split("").reverse().forEach((value, index) => {
arr.push(value)
if ((index + 1) % 3 == 0 && index + 1 != String(num).split("").reverse().length) {
arr.push(",")
}
})
return arr.reverse().join("")
}