js和wxs精确四舍五入,保留两位小数

js:toFix方法为银行家算法,0.15会算成0.01,所以舍弃

var num =2.446242342;
num = Math.round((num + Number.EPSILON) * 100) / 100;  // 输出结果为 2.45

wxs:

var toFixedFn = function (x) {
        var f = parseFloat(x);
        if (isNaN(f)) {
            return '0.00';
        }
        var f = Math.round(x * 100) / 100;
        var s = f.toString();
        var rs = s.indexOf('.');
        if (rs < 0) {
            rs = s.length;
            s += '.';
        }
        while (s.length <= rs + 2) {
            s += '0';
        }
        return s
    }

使用示例:

<wxs module="m1">
    var toFixedFn = function (x) {
        var f = parseFloat(x);
        if (isNaN(f)) {
            return '0.00';
        }
        var f = Math.round(x * 100) / 100;
        var s = f.toString();
        var rs = s.indexOf('.');
        if (rs < 0) {
            rs = s.length;
            s += '.';
        }
        while (s.length <= rs + 2) {
            s += '0';
        }
        return Number(s).toFixed(2);
    }
    module.exports = {
        toFixedFn: toFixedFn
    };
</wxs>

在前端小程序开发中,有多种方法可以将数字类型保留两位小数: #### 方法一:在 JavaScript 中使用 `toFixed()` 方法 在 js 文件中请求到数据显示之前处理一下,示例代码如下: ```javascript // 保留两位小数 function toFixed() { var arr = this.data.goodsList; arr.map(function (i) { // 处理请求到的数据是 null 时,赋值为0 if (i.cartProductNum === null) { i.cartProductNum = 0; } if (i.rancherPrice === null) { i.rancherPrice = 0; } // 处理数据保留两位小数,再赋值给原字段 i.price = i.price.toFixed(2); }); this.setData({ goodsList: arr }); } ``` 这种方法适用于对请求到的数据进行处理,将数据中的数字保留两位小数后再显示 [^2]。 #### 方法二:在 WXS 中定义函数 在 `utils` 里新建 `filter.wxs` 文件,示例代码如下: ```javascript var toFix = function(value) { return value.toFixed(2); // 此处2为保留两位小数保留几位小数,这里写几 }; module.exports = { toFix: toFix }; ``` 在 wxml 文件中引入并使用该函数,这种方法可以在模板中对数据进行格式化 [^3]。 #### 方法三:在输入框输入时进行限制 在输入框输入时,对输入的数字进行限制,使其只能输入两位小数,示例代码如下: ```vue <template> <input v-model="moneyInput" class="" placeholder="请输入提现金额" type="digit" placeholder-style="color:#E2E4EA;" @input="checkPrice" /> </template> <script> export default { data() { return { moneyInput: '' }; }, methods: { checkPrice(e) { let price = e.detail.value; if (price.indexOf(".") < 0 && price != "") { 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); } this.$nextTick(function() { this.moneyInput = price; }); } } }; </script> ``` 这种方法适用于输入框输入时对输入的数字进行实时校验处理 [^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hmk1900

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值