温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - How to use Math.round to round numbers to the nearest EVEN number?

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

发布于 2020-03-27 16:11:52

请仅使用JavaScript。

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

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

由于我是该语言的新手,所以我现在只想写一部分-“ band size”

I have an input field for users to type in their "under bust measurement" which I currently have set to round. This works as it intended. See here

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

However, I don't need the input 'underBust' to round to the nearest whole number. I need it to round to the nearest EVEN whole number, since bra band sizes only come in even whole numbers.

For example, if the user inputs the number "31.25" the code would currently round it to "31" but I need it to round it to "32"

If the user inputs the number "30.25" the code would round it correctly to "30" because the nearest whole number and nearest whole even number are the same in this case. However, if the user inputs "30.5" the code would round it up to "31" but I still need it to round down to "30"

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

这可能吗?

查看更多

查看更多

提问者
user3426725
被浏览
15
Bergi 2014-03-17 04:54

应该这样做:

2 * Math.round(underbust / 2);

发布
问题

分享
好友

手机
浏览

扫码手机浏览