分享一个好用的处理数字的JS方法

需求背景

有的输入框需要限制输入类型,比如数字,但是原有的type="number"并不好用,有的还需要精确到多少分位、是否有小数点、负数、中英文等等,于是就写了这个方法

具体方法如下

/**
 *
 * @param @allowOther 允许英文和其他字符
 * @param @allowNegativeNum 允许负数
 * @param @allowPoint 允许小数点
 * @param @fixed 精确到多少分位
 * @param @maxValue 最大值
 * @param @minValue 最小值
 * @param @maxLen 最长长度
 * @param @extraRules 自定义处理函数
 */
export const dealInput = function (val, options = {}) {
  console.log(val, 'dealInput val')
  val = val.replace(/,/g, '')
  val = val.replace(/^0*(0\.|[1-9])/, '$1') // 解决 粘贴不生效
  if (!options.allowOther) {
    if (options.allowPoint) {
      if (options.allowNegativeNum) {
        val = val.replace(/[^\-\d.]/g, '') // 清除“-“,“数字”和“.”以外的字符
      } else {
        val = val.replace(/[^\d.]/g, '') // 清除“-“,“数字”和“.”以外的字符
      }

      val = val
        .replace('.', '$#$') //第一个 . 换成 $#$
        .replace(/\./g, '') //去掉其他的 .
        .replace('$#$', '.') //$#$ 换成 . 从而 只保留第一个. 清除多余的

      val = val
        .replace('-', '&#&') //第一个 . 换成 &#&
        .replace(/-/g, '') //去掉其他的 .
        .replace('&#&', '-') //&#& 换成 . 从而 只保留第一个. 清除多余的
    } else {
      if (options.allowNegativeNum) {
        val = val.replace(/[^\-\d]/g, '') // 清除“-“,“数字”以外的字符
      } else {
        val = val.replace(/[^\d]/g, '') // 清除“-“,“数字”以外的字符
      }
    }
  }

  const fixReg = new RegExp('^(-)*(\\d*?)\\.(\\d{1,' + options.fixed + '}).*$')
  val = val.replace(fixReg, '$1$2.$3') // 只能输入N个小数,小数点前面可以没有数字
  if (val.indexOf('.') < 0 && val !== '') {
    // 如果没有小数点,首位不能为类似于 01、02的金额
    if (val.substr(0, 1) === '0' && val.length === 2) {
      val = val.substr(1, val.length)
    }
  }

  if (val.indexOf('.') === 0 && val.length > 1) {
    // 如果第一个字符时“.”,那么当“.”后面有数字后,"."前面自动补零
    val = 0 + val
  }
  if (options.minValue) {
    if (val && Number(val) < Number(options.minValue)) {
      val = ''
    }
  }
  if (options.maxValue) {
    if (Number(val) > Number(options.maxValue)) {
      if (options.fixed) {
        val = options.maxValue.toFixed(options.fixed)
      } else {
        val = options.maxValue
      }
    }
  }
  if (options.maxLen) {
    const hadNegativeNum = val.indexOf('-') > -1
    let maxLen = hadNegativeNum ? options.maxLen + 1 : options.maxLen
    if (options.fixed) {
      const numArr = String(val).split('.')
      if (numArr.length > 1) {
        const preStr = numArr[0]
        const afterStr = numArr[1]
        let val1 = preStr
        let val2 = afterStr
        if (preStr.length > maxLen) {
          val1 = val.substr(0, maxLen)
        }
        if (afterStr.length > options.fixed) {
          val2 = val.substr(maxLen, -1)
        }
        val = val1 + '.' + val2
      } else {
        if (val.length > maxLen) {
          val = val.substr(0, val.length - 1) // 截取除最后一个字符
        }
      }
    } else {
      if (val.length > maxLen) {
        val = val.substr(0, val.length - 1) // 截取除最后一个字符
      }
    }
  }
  if (options.extraRules) {
    val = options.extraRules(val)
  }
  return val
}

具体使用

<template>
  <div style="border: 1px solid #000; padding: 10px">
    {{ val }}
    <CommonInput
      :initVal="val"
      :attr="{
        label: '金额',
        placeholder: '请输入金额',
      }"
      @emitVal="
        (ev) => {
          val = ev.value
        }
      "
      :customProcessingFn="customProcessingFn"
    />
  </div>
</template>

<script setup>
const val = ref('')
const customProcessingFn = (value) => {
  console.log(value)

  return dealInput(value, {
    allowPoint: true,
    fixed: 2,
  })
}
</script>

<style lang="scss" scoped>
button {
  margin: 10px;
  padding: 10px;
  border: 1px solid #000;
  border-radius: 5px;
}
</style>

<input
  type="text"
  class="card-number"
  v-model="cardNumber"
  @input="handleInputChange"
/>
。。。。。。
。。。。。。
。。。。。。
handleInputChange(e) {
  e.target.value = dealInput(e.target.value, {
    allowPoint: false,
    maxLen: 4,
  })
  this.cardNumber = e.target.value
},

好用记得点赞收藏关注哦!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老电影故事

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值