问题:数字要保留两位小数,但是重写toFixed,大部分数据已经可以四舍五入,但是1.005类似的数据,四舍五入之后得到的数据是1.00,其实应该是1.01,求大神指点;
Number.prototype.toFixed = function (num) {
var changenum = (Number(this * Math.pow(10, num) + 0.5) / Math.pow(10, num)).toString();
index = changenum.indexOf(".");
if (index < 0 && num > 0) {
changenum = changenum + ".";
for (i = 0; i < num; i++) {
changenum = changenum + "0";
}
} else {
index = changenum.length - index;
for (i = 0; i < (num - index) + 1; i++) {
changenum = changenum + "0";
}
}
return changenum;
};
1.005*100=100.5,Math.round四舍五入,得101再除100得1.01,能不能这样
写的不大细
将var reg = /.(d{3})d+$/;改为了var reg = /.(d{3})d*$/;
num != Number改为num != 'number'