react input限制数字输入时候只能输入两位小数,输入多了会自动保留两位

react input限制数字输入时候只能输入两位小数,输入多了会自动保留两位

文件utils,放的是公用方法

/**
 * 保留2位小数 不够位数,则用0替补
 * */
function toDecimal2(num) {
    let result = Math.floor(num * 100) / 100;
    let s_x = result.toString(); //将数字转换为字符串
    let pos_decimal = s_x.indexOf('.'); //小数点的索引值
    // 当整数时,pos_decimal=-1 自动补0
    if (pos_decimal < 0) {
        pos_decimal = s_x.length;
        s_x += '.';
    }
    // 当数字的长度< 小数点索引+2时,补0
    while (s_x.length <= pos_decimal + 2) {
        s_x += '0';
    }
    return s_x;
}
 <div className=" change_box">
            <span className="btbnone">入厂重量</span>
            <span className="btbnone">{weighingLine.gross_weight}吨</span>
            <span className="btbnone"><Input  value={gross_weight} placeholder="请输入变更吨数" onChange={(e) => {getsAferGross(e)}}></Input></span>
          </div>
          <div className="change_line2 change_box">
            <span className="btbnone">出厂重量 </span>
            <span className="btbnone">{weighingLine.tare_weight}吨</span>
            <span className="btbnone"><Input  value={tare_weight} placeholder="请输入变更吨数" onChange={(e) => {getAfterTare(e)}}></Input></span>
          </div>
let [timeoutId1,setTimeoutId1] = useState('')
let [timeoutId2,setTimeoutId2] = useState('')


const getsAferGross = (e) => {
    let val = e.currentTarget.value
    let teg = /^\d+(\.\d{1,2})?$/
    teg.test(val)
    if (teg.test(val)==false){
      message.error('只能保留到小数点后两位~')
    }
    let num = JSON.parse(JSON.stringify(val))
    let num1 = utils.toDecimal2(num)
    if (timeoutId1 !== null) {
      clearTimeout(timeoutId1);
    }
    // 设置新的定时器
    setTimeoutId1(()=>
        setTimeout(() => {
          setGross_weight(num1)
        }, 3000) // 例如,延迟300毫秒执行
    )
    setGross_weight(val)
  }
  const getAfterTare = (e) => {
    let val = e.currentTarget.value
    let teg = /^\d+(\.\d{1,2})?$/
    teg.test(val)
    if (teg.test(val)==false){
      message.error('只能保留到小数点后两位~')
    }
    let num = JSON.parse(JSON.stringify(val))
    let num1 = utils.toDecimal2(num)
    if (timeoutId2 !== null) {
      clearTimeout(timeoutId2);
    }
    // 设置新的定时器
    setTimeoutId2(()=>
        setTimeout(() => {
          setTare_weight(num1)
        }, 3000) // 例如,延迟300毫秒执行
    )
    setTare_weight(val)
  }

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值