function commafy() {
var num = document.getElementById("NumA").value;
//1.先去除空格,判斷是否空值和非數
num = num + "";
num = num.replace(/[ ]/g, "");
if (num == "") {
alert("空值,結束");
return;
}
if (isNaN(num)) {
alert("非數,結束");
return;
}
//2.針對是否有小數點,分情況處理
var index = num.indexOf(".");
if (index==-1) {//無小數點
var reg = /(-?d+)(d{3})/;
while (reg.test(num)) {
num = num.replace(reg, "$1,$2");
}
} else {
var intPart = num.substring(0, index);
var pointPart = num.substring(index + 1, num.length);
var reg = /(-?d+)(d{3})/;
while (reg.test(intPart)) {
intPart = intPart.replace(reg, "$1,$2");
}
num = intPart +"."+ pointPart;
}
return alert(num);
}