input输入框输入正数、负数、小数并保留两位小数

复制原文
https://www.cxyzjd.com/article/brevey/107543470
https://blog.csdn.net/return_js/article/details/102840141

这是是直接从这位大佬的博客拿过来做的整理,亲测有效
保留两位小数方法链接
https://blog.csdn.net/return_js/article/details/102840141

HTML:

<input  v-model="data"  @input.native="data= data.replace(data,RestrictedMoney(data))">

js:

plusOrMinus(values) {
      let newValue;
      if (!(/[^0-9.-]/g.test(values))) {
        newValue = values.replace(/[^\-\d.]/g, '').replace(/\-{2,}/g, '-').replace(/\-{2,}/g, '-').replace(/^\./g, '')
                  .replace(/\.{2,}/g, '.')
                  .replace('.', '$#$')
                  .replace(/\./g, '')
                  .replace('$#$', '.');
        if (newValue.toString().indexOf('.') > 0 && Number(newValue.toString().split('.')[1].length) > 2) {
          newValue = parseInt(parseFloat(newValue) * 100) / 100;
        }
        if ((newValue.toString().split('-').length - 1) > 1) {
          newValue = parseFloat(newValue) || '';
        }
        if ((newValue.toString().split('-').length) > 1 && newValue.toString().split('-')[0].length > 0) {
          newValue = parseFloat(newValue) || '';
        }
        if (newValue.toString().length > 1 && (newValue.toString().charAt(0) === '0' || (newValue.toString().length > 2 && newValue.toString().charAt(0) === '-' && newValue.toString().charAt(1) === '0' && newValue.toString().charAt(2) !== '.')) && newValue.toString().indexOf('.') < 1) {
          newValue = parseFloat(newValue) || '';
        }
        // 判断整数位最多为9位
        if (newValue.toString().indexOf('.') > 0 && Number(newValue.toString().split('.')[0].length) > 9) {
          newValue = `${newValue.toString().substring(0, 9)}.${newValue.toString().split('.')[1]}`;
        } else if (newValue.toString().indexOf('.') < 0 && Number(newValue.toString().split('.')[0].length) > 9) {
           newValue = newValue.toString().substring(0, 9);
         }
      } else {
         newValue = values.replace(/[^0-9.-]/g, '');
        }
      return newValue;
    },
     // 额外费用校验输入正负数, 保留2位小数 调用公共方法
    RestrictedMoney(values) {
      return this.plusOrMinus(values.toString());
    },

后续会补一些注释。
学海无涯!!!!!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值