这是我的微信小程序开发过程遇到的问题,从网上找来了一段代码,应该是js都通用的。小程序里面只需要先执行下面的方法fixToFixedIssue里的代码,就可以直接用了。经测试大量数据(见下面方法testMyToFixed),打印结果显示此方法准确可行。
onLoad: function (options) {
this.fixToFixedIssue()
this.testMyToFixed()
},
//js自带的Number.toFixed方法处理小数遇到5的时候是错误的!!有时候舍出,有时候舍入!,必须重写!
//必须在当前页面执行,否则作用范围无法覆盖当前页面
//代码来源,https://www.cnblogs.com/gushen/archive/2012/11/20/2778324.html
fixToFixedIssue: function() {
Number.prototype.toFixed = function (d) {
var s = this + "";
if (!d) d = 0;
if (s.indexOf(".") == -1) s += ".";
s += new Array(d + 1).join("0");
if (new RegExp("^(-|\\+)?(\\d+(\\.\\d{0," + (d + 1) + "})?)\\d*$").test(s)) {
var s = "0" + RegExp.$2, pm = RegExp.$1, a = RegExp.$3.length, b = true;
if (a == d + 2) {
a = s.match(/\d/g);
if (parseInt(a[a.length - 1]) > 4) {
for (var i = a.length - 2; i >= 0; i--) {
a[i] = parseInt(a[i]) + 1;
if (a[i] == 10) {
a[i] = 0;
b = i != 1;
} else break;
}
}
s = a.join("").replace(new RegExp("(\\d+)(\\d{" + d + "})\\d$"), "$1.$2");
} if (b) s = s.substr(1);
return (pm + s).replace(/\.$/, "");
} return this + "";
};
},
testMyToFixed: function () {
let testArray = [0.010, 0.0149,0.015,0.016,0.017,0.019,
0.026, 0.029, 0.02111, 0.078, 0.0711,0.0701,
0.10, 0.11, 0.145, 0.149, 0.150, 0.151, 0.155, 0.159,
1.001, 1.004,1.005, 1.006,1.009, 1.105, 1.104, 1.109,
1.6,1.0, 1.423, 1.531, 1.555, 1.504, 1.506, 1.669, 1.998,
998, 996, 910,1,12,33,151, 99999,
333.01232, 333.09139, 333.93153, 148.898342, 231.09002,
231.000002329, 21.98, 67.473, 33.234, 12.982, 12.238, 896.023,
99999.99999]
for (var i = 0; i < testArray.length; i++) {
var value = testArray[i];
console.log(value + "------" + value.toFixed(2))//0,1,2,30等都测试过,结果正确。
}
}
网友评论