天天看点

input输入金额,小数点后最多输入两位,只能输入一个小数点,只能输入小数点和数字

规则:

1、只能输入小数点和数字

2、小数点前最多输入12位,小数点后最多输入两位

3、只能输入一个小数点

4、当第一个字符输入小数点时自动变为 0.

代码:

keyupmoneyformat(){
  //只能输入小数点和数字
  this.inputValue=this.inputValue.replace(/[^0-9.]/g,'')
  this.maxlength = '15'
  //字符中是否有小数点
  if(this.inputValue.indexOf(".") != -1){
    //不能输入两个小数点================================
    let len = 0
    let arr = this.inputValue.split("")
    arr.forEach((item) => {
      if(item == '.'){
        len++
      }
    })
    if(len == 1){
      this.stag = this.inputValue.split(".")
    } else if(len > 1){
      this.inputValue = this.stag[0] + '.' + this.stag[1]
    }
    
    //小数点后只能输入两位、当第一个字符输入小数点时,自动改为0.=========================
    let str = this.inputValue.split(".")
    if(this.inputValue == '.'){
      this.inputValue=this.inputValue.replace(/[.]/g,'0.')
    }
    if(str[1] && str[1].length == 2){
      this.lastValue = str[1]
    }
    if(str[1] && str[1].length > 1){ 
      this.inputValue = str[0] + '.' + this.lastValue
    }
  }else{
    //小数点前最多输入12位==========================================
    if(this.inputValue.length == 13){
      let lastStr = this.inputValue.substr(this.inputValue.length-1,1)
      if(lastStr !== '.'){
        let arr = this.inputValue.split('');
        arr.splice(arr.length - 1);
        let str2 = arr.join('');
        this.inputValue = str2; 
      }
    }
  } 
}
           

继续阅读