最近做的小程序项目里,需要根据用户实时输入来计算优惠价,这就需要控制用户输入的只能是金额,首先需要规定input的type:
<input value="{{money}}" type="digit" bindinput="bindMoneyInput"/>
然后在js相应的方法里使用控制输入只能是金额的公共方法:
bindMoneyInput(e) {
const moneyVal = publicMoneyInput(e)
}
公共方法:
export const publicMoneyInput = (e) => {
let moneyVal = e.detail.value;
let str = moneyVal.split(".")
// 控制不能输入两个小数点
if (str.length - 1 > 1) {
if (moneyVal == '0..') {
moneyVal = '0.'
}
moneyVal = moneyVal
}
// 控制不能输入00.xx
if (str[0].length > 1) {
if (str[0].indexOf(0) == '0') {
// console.log('数字格式不正确!');
moneyVal = '';
}
}
if (moneyVal == '.') {
moneyVal = moneyVal.replace(/[.]/g, '0.')
}
if (str[1]) {
if (str[1].length <= 2) {
moneyVal = str[0] + '.' + str[1]
} else {
moneyVal = str[0] + '.' + str[1].slice(0, 2)
}
}
return moneyVal
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。