Javascript-将1,675舍入为1,67-默认情况下将其舍入为1,68

问题描述 投票:-3回答:1

任何想法如何将1.675舍入为1.67

默认情况下,它四舍五入为1.68

Math.round(1.675 * 100) / 100; // 1.68

顺便说一下,如果数字为1.676,它仍应按预期四舍五入为1.68

javascript jquery rounding
1个回答
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. 请输入您的电话号码1.675
  2. 获取其绝对值1.675(这是负数)
  3. 否定-1.675
  4. 使用round()获得最接近+∞-1.67的值
  5. 如果最初是正数,则取反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
© www.soinside.com 2019 - 2024. All rights reserved.