Warm tip: This article is reproduced from stackoverflow.com, please click
javascript rounding

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

发布于 2020-03-27 15:46:00

Using JavaScript only please.

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.

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"

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"

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.

Is this possible?

Questioner
user3426725
Viewed
16
Bergi 2014-03-17 04:54

This should do it:

2 * Math.round(underbust / 2);