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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22442831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:10:06  来源:igfitidea点击:

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

javascriptrounding

提问by user3426725

Using JavaScript only please.

请只使用 JavaScript。

This is the first time I am attempting to write JavaScript on my own. I've successfully manipulated codes that friends have written for me in the past, but I have never written my own from scratch, nor took the time to try and understand the language itself until recently.

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

I'm trying to make a basic bra size calculator that takes numbers (measurements) from user input, routes them into a function and returns (calculates) a bra size to the user.

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

Since I'm so new to this language, I'm only trying to write one part right now - "band size"

由于我对这种语言很陌生,所以我现在只想写一个部分 - “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.

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

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"

例如,如果用户输入数字“31.25”,代码当前会将其四舍五入为“31”,但我需要将其四舍五入为“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"

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

Basically, I need the number to be rounded UP if the user input is equal to or greater than an odd number (29.00 becomes 30, 31.25 becomes 32, etc.). If the user input is greater than or equal to an even number and less than the next odd number (28, 28.25, 28.75, etc.) I need it to round down (in the previous example, to 28 for all cases). The odd number is the middle divide for rounding, instead of the ".5" of any number.

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

Is this possible?

这可能吗?

回答by Bergi

This should do it:

这应该这样做:

2 * Math.round(underbust / 2);

回答by Henrik

If you also wish to format, building on @Bergi's answer:

如果您还想格式化,请以@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 ]
}

Very useful when you want un-biased rounding. Usage:

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

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

Refs

参考文献

回答by Bocho Todorov

I am an absolute amateur, but I made in a wrong way

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

2 * parseInt(value/2)

2 * parseInt(值/2)

But it did exactly what I needed - Math.round rounds it by 0,5 ParseInt did it at 0

但这正是我所需要的 - Math.round 将它舍入了 0,5 ParseInt 在 0 时做到了