vue js对input输入数字后两位(金额输入框)

js控制input框只能输入数字和一位小数点和小数点后面两位小数

html代码

 <input id="money" type="number" step="1" 
  pattern="number" class="form-control" placeholder="¥ 输入付款金额" 
  aria-label="Example text with button addon">

js代码

// 金额计算
	$("#money").on('input  propertychange',function(){
			//如果输入非数字,则替换为''
			this.value = this.value.replace(/[^\d\.]/g, '');
			//必须保证第一个为数字而不是.     
		    this.value = this.value.replace(/^\./g,'');
		    //保证只有出现一个.而没有多个.     
		    this.value = this.value.replace(/\.{2,}/g,'.');
		    //保证.只出现一次,而不能出现两次以上     
		    this.value = this.value.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
		    //只能输入两位小数
		    this.value = this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');
		 this.value = this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
					if (this.value.indexOf(".") < 0 && this.value != "") { //以上已经过滤,此处控制的是如果没有小数点,首位不能为类似于 01、02的金额 
						this.value = parseFloat(this.value);
					}
		})
		$("#money").blur(function(){
				//如果输入框为空,则替换为0.00
				if(this.value == ""){
					this.value = "0.00";
				}
			})

vue限制

<input ref="price" type="text"   @input="handleAmountChange" v-model.number.trim="totalval" />

js 代码

handleAmountChange(e) {
      //过滤e字符
      e.target.value = e.target.value.replace("e", "");
      
      //判断输入是数字和.
      e.target.value = e.target.value.replace(/[^\d.]/g, "");
      
      this.totalval = e.target.value;
     
      // 必须保证第一个为数字而不是.
      this.totalval = this.totalval.replace(/^\./g, "0.");
      
      // 保证只有出现一个.而没有多个.
      this.totalval = this.totalval.replace(/\.{2,}/g, ".");

      // 保证.只出现一次,而不能出现两次以上
      e.target.value = e.target.value
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");

      //只能输入两个小数
      this.totalval = this.totalval.replace(/^()*(\d+)\.(\d\d).*$/, "$1$2.$3");

    },

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值