微信小程序 —— 保留两位小数

两种方法
一:
在 utils 文件夹中新建一个 filters.wxs 文件
将下面代码写入

var filters = {
  toFix: function (value) {
    return value.toFixed(2) // 此处2为保留两位小数,保留几位小数,这里写几    
  }
}

module.exports = {
  toFix: filters.toFix,
  toNumber: filters.toNumber,
}

之后在要使用的 wxml 页面中引入

<wxs module="filters" src="../../../utils/filters.wxs"></wxs>

使用时:

<text >¥{{  filters.toFix( goodsDetail.rancherPrice )  }}</text>

第二:
在 js 文件中请求到数据显示之前处理一下

// 保留两位小数
  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
    });
  },

之后在请求数据的函数中运行此函数

posted @ 2022-10-13 23:14  土小狗  阅读(1273)  评论(0编辑  收藏  举报