根據使用者需求,在輸入金額時要格式化,即每三位數字加逗號分隔,並保留兩位小數。
考慮使用者的體驗,隨使用JS對金額進行格式化,前台代碼如下:
JS程式碼如下:
//======檢查輸入的是否為數字
function check() {
if (!((window.event.keyCode >= 48 && window.event.keyCode
window.event.keyCode = 0
}
}
//======格式化文字方塊的金額
function run(obj) {
var objvalue = obj.value.replace(/[,]/g, ""),
objlength = objvalue.length,
dtmp = objvalue.indexOf("."),
neg = objvalue.indexOf("-");
var inttmp = 0,
floattmp = -1;
if (dtmp != -1) {
inttmp = dtmp == 0 ? "0" : new String(objvalue).substring(0, dtmp);
floattmp = new String(objvalue).substring(dtmp 1, objlength 1);
floattmp = floattmp.replace(/[^0-9]/g, "");
}
else {
inttmp = objvalue;
}
if (neg == 0) {
inttmp = inttmp.replace(/[-]/g, "");
}
inttmp = inttmp.replace(/[^0-9]/g, "");
var tmp = "", str = "0000";
for (; inttmp.length > 3; ) {
var temp = new String(inttmp / 1000);
if (temp.indexOf(".") == -1) {
tmp = ",000" tmp;
inttmp = temp;
}
else {
var le = 新 String(temp).split(".")[1].length;
tmp = "," new String(temp).split(".")[1] str.substring(0, 3 - le) tmp;
inttmp = 新 String(temp).split(".")[0];
}
}
inttmp = inttmp tmp;
obj.value = neg == 0 ? "-" inttmp runing(floattmp) : inttmp runing(floattmp);
}
//======整理小數部分
function runing(val) {
if (val != "-1" && val != "") {
var valvalue = 0 "." val;
if (val.length >= 2) {
valvalue = parseFloat(valvalue).toFixed(2);
}
var temp = "." valvalue.split(".")[1];
return temp;
}
else if (val != "0" && val == "") {
return ".";
}
else {
return "";
}
}
同時因為金額可輸入負數,所以加上「neg = objvalue.indexOf("-")」的判斷。
關於金額的格式化問題,常常遇到這種事情,覺得這個還可以,也就留著,以供以後查閱方便!