在前端應該滿有機會需要用 js 把數字轉換為千分位(comma)的,應該是用正規表達式最方便:
let num1="12345";
let comma=/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g
let num2=num1.replace(comma, ',')
console.log(num2) //12,345
不過因為 replace 一定要是字串,所以最好是在做一個轉換成字串後再丟到 replace 的動作。
let num2=num1.toString().replace(comma, ',')
寫成 function:
function numberComma(num){
let comma=/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g
return num.toString().replace(comma, ',')
}
console.log(numberComma(num1))