JS
/**
* 货币,价格,保留两位数
* @param that
* @param maxLen 保留数值的长度
*/
function onlyDecimal(that, maxLen) {
that.value = that.value.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
that.value = that.value.replace(/^\./g, ""); //验证第一个字符是数字
that.value = that.value.replace(/\.{2,}/g, "."); //只保留第一个, 清除多余的
that.value = that.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
that.value = that.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
if (!(typeof maxLen == 'undefined' || maxLen == '' || maxLen == null) && that.value.length > maxLen) {
var val = that.value;
that.value = val.toString().substring(0, parseInt(maxLen))
}
}
html
<input type='text' onchange="onlyDecimal(this,5)" oninput="onlyDecimal(this,5)">