发布于 4年前

微信小程序 input 输入框限制只能输入小数点后最多两位的数字

wxml

<input type='text' type="digit" bindinput="handleInput" placeholder='价格' name="price"></input>

js

  handleInput:function(e) {
      let price = e.detail.value;

      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);
      }

     return {
         value: price,
     }
  }

相关文档 https://developers.weixin.qq.com/miniprogram/dev/component/input.html

©2020 edoou.com   京ICP备16001874号-3