【问题标题】:How to use Math.round to round numbers to the nearest EVEN number?如何使用 Math.round 将数字四舍五入到最接近的偶数?
【发布时间】:2014-04-21 23:27:26
【问题描述】:

请仅使用 JavaScript。

这是我第一次尝试自己编写 JavaScript。我已经成功地操纵了过去朋友为我编写的代码,但我从来没有从头开始编写自己的代码,直到最近也没有花时间尝试理解语言本身。

我正在尝试制作一个基本的胸罩尺寸计算器,它从用户输入中获取数字(测量值),将它们路由到一个函数中,然后将胸罩尺寸返回(计算)给用户。

由于我对这门语言还很陌生,所以我现在只尝试写一个部分——“band size”

我有一个输入字段供用户输入他们目前已设置为四舍五入的“胸围测量值”。这按预期工作。看这里

<html>

<head>

<script type="text/javascript">

 function calculate() 
  {
   var underbust = document.getElementById("underBust").value;

    if (underbust.length === 0) 
     {
      alert("Please enter your underbust measurement in inches");
      return;
     }

    document.getElementById("bandsize").innerHTML = Math.round(underbust);
   }

</script>

</head>

<body>
<input type="number" id="underBust" /> inches<br>
<input type="submit" value="Submit" onclick="calculate()" /><br>
<b>underbust:</b> <div id="bandsize">bandsize will appear here</div><br>
</body>

</html>

但是,我不需要将输入“underBust”四舍五入到最接近的整数。我需要它四舍五入到最接近的偶数整数,因为胸罩带的尺寸只有偶数。

例如,如果用户输入数字“31.25”,代码当前会将其四舍五入为“31”,但我需要将其四舍五入为“32”

如果用户输入数字“30.25”,代码会将其正确舍入为“30”,因为在这种情况下最接近的整数和最接近的整数偶数相同。但是,如果用户输入“30.5”,代码会将其四舍五入为“31”,但我仍需要将其向下舍入为“30”

基本上,如果用户输入等于或大于奇数(29.00 变为 30,31.25 变为 32,等等),我需要将数字向上取整。如果用户输入大于或等于偶数且小于下一个奇数(28、28.25、28.75 等),我需要将其向下舍入(在前面的示例中,所有情况下都为 28)。奇数是四舍五入的中间除数,而不是任何数字的“.5”。

这可能吗?

【问题讨论】:

    标签: javascript rounding


    【解决方案1】:

    应该这样做:

    2 * Math.round(underbust / 2);
    

    【讨论】:

    • 谢谢!我觉得这是一些我应该知道但没有考虑的基本数学......是的。刚做了数学,我现在觉得很愚蠢。
    • 我可以给你一个数学解释,但也许你可以通过在脑海中计算表达式来更好地理解它。
    • 最近的奇数是:2* Math.floor(n/2) + 1
    • @Nitin 否,Math.ceil(0.1) 舍入为 1(奇数),而不是 0(偶数)
    • @Henrik,我认为 Nitin 指的是 2 * Math.ceil(0.1 / 2) 中的 Math.ceil(),这将给出 2 - 下一个偶数。
    【解决方案2】:

    如果您还希望格式化,请在 @Bergi 的回答基础上进行:

    function roundToEven(value) {
      return Number.isNaN(n)
        ? 0.0
        : 2 * Math.round(value / 2);
    }
    
    /**
     * Round-to-even with a fixed number of decimals (2 decimals = to cent/öre). Returns [ rounded value, formatted rounded value ].
     * @param {*} n The number to round-to-even, with the given number of decimals
     * @param {*} decimals The number of decimals in base10 to round the number at.
     */
    function roundToEvenFixed(n, decimals = 2.0) {
      if (Number.isNaN(n) || Number.isNaN(decimals)) {
        return 0.0
      }
    
      const value = (Math.round((n * Math.pow(10, decimals)) / 2) * 2) / Math.pow(10, decimals),
            formatted = value.toFixed(decimals);
    
      return [ value, formatted ]
    }
    

    当您想要无偏舍入时非常有用。用法:

    console.log(`Amount: ${roundToEvenFixed(i.quantity * i.unitPrice.amount)[1]} kr`)
    

    参考

    【讨论】:

    • 根据问题,这个答案是正确的,但是如果您正在寻找“即使距离相等,也要四舍五入”的答案(就像在某些科学情况下使用的那样)仍然存在问题有了这个答案。它越来越近,但请尝试roundToEvenFixed(0.12510, 2)。这四舍五入到 0.12,而它应该四舍五入到 0.13,因为它比 0.12 更接近 0.13。我还没有找到解决这个问题的方法。
    • @DolfAndringa 我刚刚写了这个:gist.github.com/eeeps/75a31a2e1815b8bd4bf621de890f47e4 使用您描述的策略四舍五入到整数。要四舍五入到固定的小数位数,您可以使用roundToEvenIfEquidistant( n * 100 ) / 100
    【解决方案3】:

    我是一个绝对的业余爱好者,但我做错了

    2 * parseInt(value/2)

    但它完全符合我的需要 - Math.round 将其四舍五入 0,5 ParseInt 在 0 时做到了

    【讨论】:

    • 这是错误的,因为2*parseInt(1.5/2) = 0,但应该是2
    猜你喜欢
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 2011-03-25
    • 2012-03-07
    相关资源
    最近更新 更多