任何想法如何将1.675
舍入为1.67
?
默认情况下,它四舍五入为1.68
:
Math.round(1.675 * 100) / 100; // 1.68
顺便说一下,如果数字为1.676
,它仍应按预期四舍五入为1.68
。
我们需要更深入地了解它首先出现...
[ECMA-262这样定义Math.round()
:
返回最接近自变量且等于数学整数的数字值。 如果两个整数值相等地接近自变量,则结果是更接近+∞的数值。如果参数已经是整数,则结果就是参数本身。
粗体部分很重要,因为您将获得以下结果:
Math.round(1.674 * 100) / 100; // 1.67
Math.round(1.675 * 100) / 100; // 1.68 (wrong)
Math.round(1.676 * 100) / 100; // 1.68
Math.round(-1.674 * 100) / 100; // -1.67
Math.round(-1.675 * 100) / 100; // -1.67
Math.round(-1.676 * 100) / 100; // -1.68
请查看负数,了解其工作原理!
如果要反转1.675
的四舍五入值,则不能使用Math.floor()
,因为这会改变所有其他结果:
Math.floor(1.674 * 100) / 100; // 1.67
Math.floor(1.675 * 100) / 100; // 1.67
Math.floor(1.676 * 100) / 100; // 1.67 (wrong)
Math.floor(-1.674 * 100) / 100; // -1.68 (wrong)
Math.floor(-1.675 * 100) / 100; // -1.68 (wrong)
Math.floor(-1.676 * 100) / 100; // -1.68
我的解决方案是使用它搜索最接近+∞的Javascript特殊性。
1.675
1.675
(这是负数)-1.675
round()
获得最接近+∞-1.67
的值1.67
概念证明:
function _round(value, precision) {
var shift = Math.pow(10, precision);
var negateBack = Math.abs(value) / -value;
return Math.round(Math.abs(value) * -1 * shift) / shift * negateBack;
}
_round(1.674, 2); // 1.67
_round(1.675, 2); // 1.67
_round(1.676, 2); // 1.68
_round(-1.674, 2); // -1.67
_round(-1.675, 2); // -1.67
_round(-1.676, 2); // -1.68