今天写代码的时候遇到了个bug,就是计算金额的时候有个四舍五入,平常都是用toFixed方法来计算,而今天碰到了一个数,很是奇怪,就是1.335用toFixed方法算出来是1.33,代码如下:
Number(1.335).toFixed(2); // 输出1.33
这时候可能会有人给出解决办法,就是原来的数乘以100,然后用Math.round()进行四舍五入,然后再除以100,代码如下:
Math.round(Number(1.335) * 100) / 100 // 输出1.34
那如果换个数呢
Math.round(Number(8765.335) * 100) / 100 // 输出8765.33
还是没解决刚才的问题,这就很无语了。如果这个方法不能用就只能寄几想办法了,重写toFixed方法,代码如下:
Number.prototype.toFixed = function (n) {
if (n != undefined && (isNaN(n) || Number(n) > 17 || Number(n) < 0)) {
throw new Error("输入正确的精度范围");
}
// 拆分小数点整数和小数
var num = this;
var f = '';
if (Number(num) < 0) {
num = -Number(num);
f = '-';
}
var numList = num.toString().split(".");
// 整数
var iN = numList[0];
// 小数
var dN = numList[1];
n = parseInt(n);
if (isNaN(n) || Number(n) === 0) {
// 0或者不填的时候,按0来处理
if(dN === undefined){
return num + '';
}
var idN = Number(dN.toString().substr(0, 1));
if (idN >= 5) {
if (Number(iN) < 0) {
iN = Number(iN) - 1
} else {
iN = Number(iN) + 1
}
}
return iN + '';
} else {
var dNL = dN === undefined ? 0 : dN.length;
if (dNL < n) {
// 如果小数位不够的话,那就补全
var oldN = num.toString().indexOf('.') > -1 ? num : num + '.';
var a = Number(n) - dNL;
while (a > 0) {
oldN += '0';
a--;
}
return oldN;
}
// 正常
var olddN = dN.toString().substring(0, n);
var dN1 = Number(dN.toString().substring(0, n));
var dN2 = Number(dN.toString().substring(n, n + 1));
if (dN2 >= 5) {
dN1 += 1;
if (olddN.length - dN1.toString().length > 0) {
var olddNL = olddN.length - dN1.toString().length
while (olddNL > 0) {
dN1 = '0' + dN1
olddNL--;
}
}
if (dN1.toString().length > n) {
if (Number(iN) < 0) {
iN = Number(iN) - 1
} else {
iN = Number(iN) + 1
}
dN1 = '0';
while (n > 1) {
dN1 += '0'
n--;
}
}
} else {
dN1 = olddN
}
return f + iN + '.' + dN1;
}
}
写了一些测试数据
console.log(240.025,240.025.toFixed(2))
console.log(240.005,240.005.toFixed(2))
console.log(240.995,240.995.toFixed(2))
console.log(240.905,240.905.toFixed(2))
console.log(249.905,249.905.toFixed(2))
console.log(249.995,249.995.toFixed(2))
console.log(99.995,99.995.toFixed(2))
console.log(0.995,0.995.toFixed(2))
console.log(0.5,0.5.toFixed(2))
console.log(0.95,0.95.toFixed(2))
console.log(0.995,0.995.toFixed(2))
console.log(0.594,0.594.toFixed(2))
console.log(0.004,0.004.toFixed(2))
console.log(0.005,0.005.toFixed(2))
console.log(0.095,0.095.toFixed(2))
如果写的不好的地方,谢谢指出