tofixed(),四舍六入五凑偶,修改成四舍五入
方法一:
在JS中四舍五入的函数 toFixed(n) , n为要保留的小数位数。 n为0~20,当n超过20的时候,JS会出错。
不同的浏览器,或者是一些特别的数字,这个方法就不会按常理截取。
var h=0.155
h.toFixed(2)的值为0.15
其实要解决这个问题,原来是不一定要重写js中的Number类型的toFixed方法的。
一个很牛的方法是:使用toFixed方法之前加1,使用之后再减去1。
var num = 0.007;//要四舍五入的数字
var fixNum = new Number(num+1).toFixed(2);//四舍五入之前加1
var fixedNum = new Number(fixNum - 1).toFixed(2);//四舍五入之后减1,再四舍五入一下
alert(fixedNum);//弹出的数字就是正确的四舍五入结果啦
方法二:
重写toFixed的脚本方法
// toFixed兼容方法
Number.prototype.toFixed = function (n) {
if (n > 20 || n < 0) {
throw new RangeError('tofixed()数字参数必须是0和20之间');
}
const number = this;
if (isNaN(number) || number >= Math.pow(10, 21)) {
return number.toString();
}
if (typeof (n) == 'undefined' || n == 0) {
return (Math.round(number)).toString();
}
let result = number.toString();
const arr = result.split('.');
// 整数的情况
if (arr.length < 2) {
result += '.';
for (let i = 0; i < n; i += 1) {
result += '0';
}
return result;
}
const integer = arr[0];
const decimal = arr[1];
if (decimal.length == n) {
return result;
}
if (decimal.length < n) {
for (let i = 0; i < n - decimal.length; i += 1) {
result += '0';
}
return result;
}
result = integer + '.' + decimal.substr(0, n);
const last = decimal.substr(n, 1);
// 四舍五入,转换为整数再处理,避免浮点数精度的损失
if (parseInt(last, 10) >= 5) {
const x = Math.pow(10, n);
result = (Math.round((parseFloat(result) * x)) + 1) / x;
result = result.toFixed(n);
}
return result;
};