1. 程式人生 > >js轉換數字為千位計數法

js轉換數字為千位計數法

1、方法一

function number_format(str) {
if (/[^0-9.-]/.test(str)) {
return “\u5fc5\u987b\u662f\u6570\u5b57\uff01”;
}
str = str.replace(/^(\d*)/,"1.”);
str = (str + “00”).replace(/(\d*.\d\d)\d*/, “1);str=str.replace(.,,);varre=/(\d)(\d3,)/;while(re.test(str))str=str.replace(re,$1,$

2);str=str.replace(/,(\d\d)/, ".$1”);
return str.replace(/^./, “0.”);
}
注:當數為20000的話,結果為:20,000.00
2、方法二

function number_format(num) {
return num && num
.toString()
.replace(/(^|\s)\d+/g, (m) => m.replace(/(?=(?!\b)(\d{3})+$)/g, ‘,’))
}
注:當數為20000的話,結果為:20,000