function formatNum(str) {
var newStr = "";
var count = 0;
// 當數字是整數
if (str.indexOf(".") == -1) {
for (var i = str.length - 1; i >= 0; i--) {
if (count % 3 == 0 && count != 0) {
newStr = str.charAt(i) + "," + newStr;
} else {
newStr = str.charAt(i) + newStr;
}
count++;
}
str = newStr ; //自動補小數點后兩位
return str;
}
// 當數字帶有小數
else {
for (var i = str.indexOf(".") - 1; i >= 0; i--) {
if (count % 3 == 0 && count != 0) {
newStr = str.charAt(i) + "," + newStr;
} else {
newStr = str.charAt(i) + newStr; //逐個字符相接起來
}
count++;
}
str = newStr + (str + "00").substr((str + "00").indexOf("."), 3);
return str;
}
}
formatNum('13213.24'); //輸出13,213.34
formatNum('132134.2'); //輸出132,134.20
formatNum('132134'); //輸出132,134.00
formatNum('132134.236'); //輸出132,134.23