微信小程序 input 输入框限制只能输入小数点后最多两位的数字
wxml
<input value="{{price}}" type="digit" bindinput="handleInput" placeholder='价格' name="price"></input>
注*:小程序input中type属性
type=“text” 全键盘模式输入
type=“number” 纯数字键盘模式输入
type=“digit” 带小数点的数字键盘模式输入
方法一:
Js
handleInput:function(e) {
let price = e.detail.value;
let that = this;
price = price.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
price = price.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
price = price.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
price = price.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数
if (price.indexOf(".") < 0 && price != "") {//以上已经过滤,此处控制的是如果没有小数点,首位不能为类似于 01、02的金额
price = parseFloat(price);
}
that.setData({
price : price ,
});
return {
value: price,
}
}
方法二:正则表达式
handleInput:function(e) {
//输入框限制只能输入到小数点后两位
e.detail.value = e.detail.value.match(/^\d*(\.?\d{0,2})/g)[0]) || null
let price = e.detail.value;
let that = this;
that.setData({
price : price ,
});
return {
value: price,
}
}
版权声明:本文为weixin_43927397原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。