input 小数点后边保留一位小数

<input class="input" v-model="heightVal" @input="handleInput('height')" />

<input class="input" v-model="weightVal" @input="handleInput('weight')" />
 
handleInput (type) {
  let val = type == 'height' ? 'heightVal' : 'weightVal'
  //清除"数字"和"."以外的字符
  this[val] = this[val].replace(/[^\d.]/g,"") 
  //验证第一个字符是数字
  this[val] = this[val].replace(/^\./g,"") 
  //只保留第一个, 清除多余的  
  this[val] = this[val].replace(/\.{2,}/g,"") 
  this[val] = this[val].replace(".","$#$").replace(/\./g,"").replace("$#$",".")
  //只能输入一位小数
  // eslint-disable-next-line no-useless-escape
  this[val] = this[val].replace(/^(\-)*(\d+)\.(\d).*$/,'$1$2.$3') 
  //以上已经过滤,此处控制的是如果没有小数点,首位不能为类似于 01、02的金额
  if(this[val].indexOf(".")< 0 && this[val] !="") this[val]= parseFloat(this[val]) 
}
posted @ 2022-09-14 14:21  搬砖的苦行僧  阅读(398)  评论(0编辑  收藏  举报