input 保留兩位小數 並且只能有一個小數點


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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM