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>