According to user needs, format the amount when entering it, that is, separate every three digits with commas and retain two decimal places.
Considering the user experience, JS is used to format the amount. The front-end code is as follows:
The JS code is as follows:
//======Check whether the input is a number
function check() {
if (!((window.event.keyCode >= 48 && window.event.keyCode <= 57) || window.event.keyCode == 46 || window.event.keyCode == 45)) {
window.event.keyCode = 0
}
}
//======Format the amount of the text box
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 = new String(temp).split(".")[1].length;
tmp = "," new String(temp).split(".")[1] str.substring(0, 3 - le) tmp;
inttmp = new String(temp).split(".")[0];
}
}
inttmp = inttmp tmp;
Obj.value = neg == 0 ? "-" inttmp running(floattmp) : inttmp running(floattmp);
}
//======Organize the decimal part
function running(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 "";
}
}
At the same time, because the amount can be entered as a negative number, the judgment of "neg = objvalue.indexOf("-")" is added.
Regarding the formatting problem of amounts, I often encounter this kind of thing. I think this is okay, so I will keep it for future reference!