码迷,mamicode.com
首页 > 其他好文 > 详细

input 保留两位小数 并且只能有一个小数点

时间:2020-10-31 02:33:03      阅读:7      评论:0      收藏:0      [点我收藏+]

标签:fun   ntp   mod   之间   length   ast   cti   hat   pre   

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>

 

input 保留两位小数 并且只能有一个小数点

标签:fun   ntp   mod   之间   length   ast   cti   hat   pre   

原文地址:https://www.cnblogs.com/qiusu/p/13904623.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!