是否知道如何将1.675
舍入为1.67
?
默认情况下,它会四舍五入为1.68
:
Math.round(1.675 * 100) / 100; // 1.68
顺便说一下,如果数字是1.676
,它仍应按预期四舍五入到1.68
。
答案 0 :(得分:0)
我们需要更深入地了解它首先出现的地方...
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