美文网首页程序员
input 针对价格输入限制

input 针对价格输入限制

作者: Amituofo_ | 来源:发表于2021-02-03 15:55 被阅读0次

input 针对价格输入限制

priceFormat (e) {
      this.unitPrice = (this.unitPrice.match(/^\d*(\.?\d{0,2})/g)[0]) || null
       //在不是“0.”开头的字符进行修改:“01”=>1
      if (this.unitPrice.charAt(0) == "0" && this.unitPrice.charAt(1) != "." && this.unitPrice.length >= 2) {
        this.unitPrice = this.unitPrice.replace(/0/, "")
      }
      if (isNaN(this.unitPrice)) {
        this.unitPrice = ''
      }
}
 priceFormat () {
      //非数字和小数点去掉     
      this.unitPrice = this.unitPrice.replace(/\D^./, "")
      //防止无输入无限个“.”
      this.unitPrice = this.unitPrice.replace(/\.+/, ".")
      //在不是“0.”开头的字符进行修改:“01”=>1
      if (this.unitPrice.charAt(0) == "0" && this.unitPrice.charAt(1) != "." && this.unitPrice.length >= 2) {
        this.unitPrice = this.unitPrice.replace(/0/, "")
      }
      //获取第一个小数点的索引值
      var index = this.unitPrice.indexOf('.')
      //获取最后一个小数点的索引值
      var lastIndex = this.unitPrice.lastIndexOf('.')
      //判断小数点是不是开头,如果是开头,则去除
      if (index == 0) {
        this.unitPrice = this.unitPrice.replace(/\./, "")
      }
      //只允许小数点后面有2位字符
      if (index >= 1) {
        this.unitPrice = this.unitPrice.substring(0, index + 3)
      }
      //防止小数点后面又出现小数点
      if (index != lastIndex) {
        this.unitPrice = this.unitPrice.substring(0, index + 2)
      }

    }

相关文章

网友评论

    本文标题:input 针对价格输入限制

    本文链接:https://www.haomeiwen.com/subject/ebqmtltx.html