在小程序框架中对于浮点数计算存在误差情况。
看示例:
示例1、
{{0.01+0.2}}
示例2:
-
/**
-
* 页面的初始数据
-
*/
-
data: {
-
num1: 0.01,
-
num2: 10.2,
-
},
-
this.setData({
-
num3: this.data.num1 + this.data.num2
-
})
{{num3}}
计算结果:
解决方案:
在页面显示前,使用toFixed() 方法进行四舍五入处理。
-
this.setData({
-
num4: (this.data.num1 + this.data.num2).toFixed(2)
-
})
{{num4}}
结果:10.21,显示正常。
特别说明,在视图绑定是不支持toFixed() 方法。以下为错误写法:
{{(num1+num2).toFixed(2)}}
更多:
小程序请求超时errMsg : "request:fail socket time out timeout:60000"
微信小程序Canvas隐藏问题处理
微信小程序实现多级展开功能