1.适用于uni-app小程序,可简单改造成源生小程序版

2.限制整数位只能为0-9999之间的数字

3.最多两位小数

4.首位为小数点时,变成0.

5.只能输入一个小数点

<template>
	<input class="inputPrice" :maxlength="maxLength" type="digit" v-model="currentPrice" @input="checkPrice">
</template>
<script>
	export default {
		data() {
			return {
				maxLength: 5,
				currentPrice: ''
			}
		},
		methods: {
			checkPrice: function(e) {
				let that = this;
				let price = e.detail.value
				let maxLength = price.indexOf('.');
				if (price.indexOf(".") < 0 && price != "") {
					//'超过4位则大于1万元'
					if (price.length > 4) {
						price = price.substring(0, price.length - 1)
						uni.showToast({
							title: '金额最高不能超过1万元',
							icon: 'none'
						})
					} else {
						price = parseFloat(price);
					}
				} else if (price.indexOf(".") == 0) {
					//'首位小数点情况'
					price = price.replace(/[^$#$]/g, "0.");
					price = price.replace(/\.{2,}/g, ".");
				} else if (!(/^(\d?)+(\.\d{0,2})?$/.test(price))) {
					//去掉最后一位
					price = price.substring(0, price.length - 1)
				}
				that.$nextTick(function() {
					//'有小数点时,最大长度为7位,没有则是5位'
					that.maxLength = maxLength == -1 ? 5 : 7
					that.currentPrice = price
				})

			}
		}
	}
</script>

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐