繁体   English   中英

如何使用Math.round将数字舍入到最接近的偶数?

[英]How to use Math.round to round numbers to the nearest EVEN number?

请使用JavaScript。

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

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

由于我对这种语言很陌生,我现在只想写一个部分 - “乐队大小”

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

<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”。

这可能吗?

这应该这样做:

2 * Math.round(underbust / 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`)

参考文献

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

2 * parseInt(value / 2)

但它完全符合我的要求 - Math.round将其舍入为0,5 ParseInt在0时完成

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM