我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
最简单的方法:
+num.to固定(2)
它将其转换为字符串,然后再转换为整数/浮点。
其他回答
可以使用.toFixed(小数位数)。
var str = 10.234.toFixed(2); // => '10.23'
var number = Number(str); // => 10.23
您也可以重写Math.round函数来进行舍入校正,并为小数添加一个参数,并使用它,如:Math.round(Number,decimals)。请记住,这将覆盖内置组件Math.round,并为其提供另一个属性,而不是原始属性。
var round = Math.round;
Math.round = function (value, decimals) {
decimals = decimals || 0;
return Number(round(value + 'e' + decimals) + 'e-' + decimals);
}
然后你可以这样简单地使用它:
Math.round(1.005, 2);
https://jsfiddle.net/k5tpq3pd/3/
避免舍入到任意位数的二进制问题的适当方法是:
function roundToDigits(number, digits) {
return Number(Math.round(Number(number + 'e' + digits)) + 'e-' + digits);
}
修复toFixed()函数的一种方法是:
Number.prototype.toFixed = (prototype => {
const toFixed = prototype.toFixed;
// noinspection JSVoidFunctionReturnValueUsed
return function (fractionDigits) {
if (!fractionDigits) {
return toFixed.call(this);
} else {
// Avoid binary rounding issues
fractionDigits = Math.floor(fractionDigits);
const n = Number(Math.round(Number(+this + 'e' + fractionDigits)) + 'e-' + fractionDigits);
return toFixed.call(n, fractionDigits);
}
};
})(Number.prototype);
这对我(TypeScript)起到了作用:
round(decimal: number, decimalPoints: number): number{
let roundedValue = Math.round(decimal * Math.pow(10, decimalPoints)) / Math.pow(10, decimalPoints);
console.log(`Rounded ${decimal} to ${roundedValue}`);
return roundedValue;
}
样本输出
Rounded 18.339840000000436 to 18.34
Rounded 52.48283999999984 to 52.48
Rounded 57.24612000000036 to 57.25
Rounded 23.068320000000142 to 23.07
Rounded 7.792980000000398 to 7.79
Rounded 31.54157999999981 to 31.54
Rounded 36.79686000000004 to 36.8
Rounded 34.723080000000124 to 34.72
Rounded 8.4375 to 8.44
Rounded 15.666960000000074 to 15.67
Rounded 29.531279999999924 to 29.53
Rounded 8.277420000000006 to 8.28
一个简单的解决方案是,如果你想四舍五入,可以使用Lodash的ceil函数。。。
_.round(6.001, 2)
给出6
_.ceil(6.001, 2);
给出6.01
_.ceil(37.4929, 2);
给出37.5
_.round(37.4929, 2);
给出37.49