input-数字保留小数点后2位,在vue3+typecript项目中

4 篇文章 1 订阅

input[type=numer] 虽然规避了字母和特殊字符,但又出现 0.0000不受控制的情况,故又改为 input[type=text] 用字符串的方式控制及将特殊字符替换成空字符串''

<template>
  <input  v-model="extractMoney"  maxlength="8" placeholder-style="" :placeholder="'请输入'" />
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue';
const extractMoney = ref<string | null>();

watch(extractMoney, (_newValue, _oldValue) => {
  // 小数点后两位
  if (_newValue && /^\d+(?:\.\d{0,2})?/.test(_newValue)) {
    nextTick(() => {
      extractMoney.value = String(_newValue.replace(/e/g, '').match(/^\d+(?:\.\d{0,2})?/));
    });
    return;
  }
  // 替换字母特殊字符空格
  if (_newValue && /[a-zA-Z!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\s]+/.test(_newValue)) {
    nextTick(() => {
      extractMoney.value = _newValue.replace(/[a-zA-Z!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\s]+/g, '');
    });
    return;
  }
});

const onSubmit = () => {
    const nowNumber = Number(Number(extractMoney.value).toFixed(2))
}

</script>

原生js可以用

οnkeyup="value = (String(value) || '').replace(/e/g, '').match(/^\d+(?:\.\d{0,2})?/)"

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值