可以输入小数点的数字处理即允许输入的浮点数

floatNum (sourceValue, intLen = 10, floatNum = 4) {
      //默认10位浮点数 整数位最大6位 默认可输入4位小数 必须是正整数 必须输入数字
      let tempValue = sourceValue ? sourceValue.toString() : ''
      // eslint-disable-next-line no-useless-escape
      tempValue = tempValue.replace(/[^0-9\.]/ig, '')
      if (!['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'].includes(tempValue[0])) return tempValue.slice(1)
      const dotPosition = tempValue.indexOf('.')
      const lastPosition = tempValue.length - 1
      const lastChar = tempValue[lastPosition]
      const floatLen = floatNum + 1
      const integerLen = intLen - floatLen + 1

      // 如果! (最后一位是数值 或者 是非首位并且仅有一个的小数点) 目的是保证只能输入个小数点
      if (!(!isNaN(lastChar) || (dotPosition === lastPosition && lastChar === '.'))) {
        tempValue = tempValue.slice(0, lastPosition)
      }

      if (dotPosition !== -1 && dotPosition > integerLen) { // 确保小数的位数
        tempValue = tempValue.substr(0, integerLen) + tempValue.substr(dotPosition, floatLen)
      } else if (dotPosition !== -1) {
        tempValue = tempValue.substr(0, dotPosition) + tempValue.substr(dotPosition, floatLen)
      } else {
        tempValue = tempValue.substr(0, integerLen)
      }

      return tempValue
    }

 

posted @ 2022-04-02 11:05  忽闻河东狮子吼  阅读(48)  评论(0编辑  收藏  举报