js输入框对金额的匹配
/** * 金额格式化 * @param s * @param n * @returns {String} */ function fmoney(s, n) { n = n > 0 && n <= 20 ? n : 2; s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + ""; var l = s.split(".")[0].split("").reverse(), r = s.split(".")[1]; t = ""; for (i = 0; i < l.length; i++) { t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : ""); } return t.split("").reverse().join("") + "." + r; } /** * 只能输入数字和小数点 * @param obj */ function clearNoNum(obj) { obj.value = obj.value.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符 obj.value = obj.value.replace(/^\./g, ""); //验证第一个字符是数字而不是. obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的. obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数 obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$","."); } //匹配金额并且格式化 function matchMoney(obj) { var stmp = ""; if (obj.value == stmp) { return; } else if (obj.value == ".") { obj.value = ""; return; } var ms = obj.value.replace(/[^\d\.]/g, "").replace(/(\.\d{2}).+$/, "$1").replace(/^0+([1-9])/, "$1").replace(/^0+$/, "0"); var txt = ms.split("."); while (/\d{4}(,|$)/.test(txt[0]))txt[0] = txt[0].replace(/(\d)(\d{3}(,|$))/, "$1,$2"); obj.value = stmp = txt[0] + (txt.length > 1 ? "." + txt[1] : ""); }