Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Rounding Down in .5 Cases

I am in a situation where a JavaScript function produces numbers, such as 2.5. I want to have these point five numbers rounded down to 2, rather than the result of Math.round, which will always round up in such cases (ignoring the even odd rule), producing 2. Is there any more elegant way of doing this than subtracting 0.01 from the number before rounding? Thanks.

like image 586
John E. Lepage Avatar asked Mar 06 '16 00:03

John E. Lepage


People also ask

Is 0.5 rounded up or down?

However, it can be converted to a whole number by rounding it off to the nearest whole number. 0.5 rounded off to the nearest whole number is 1. Since, the value after decimal is equal to 5, then the number is rounded up to the next whole number. Hence, the whole number of 0.5 will be 1.

How do you round down in JavaScript?

The Math. floor() method rounds a number DOWN to the nearest integer.

How do you round the number 7.25 to the nearest integer in JavaScript?

The Math. round() function in JavaScript is used to round the number passed as parameter to its nearest integer. Parameters : The number to be rounded to its nearest integer.

How do you round to 2 decimal places in math?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.


2 Answers

Just negate the input and the output to Math.round:

var result = -Math.round(-num);

In more detail: JavaScript's Math.round has the unusual property that it rounds halfway cases towards positive infinity, regardless of whether they're positive or negative. So for example 2.5 will round to 3.0, but -2.5 will round to -2.0. This is an uncommon rounding mode: it's much more common to round halfway cases either away from zero (so -2.5 would round to -3.0), or to the nearest even integer.

However, it does have the nice property that it's trivial to adapt it to round halfway cases towards negative infinity instead: if that's what you want, then all you have to do is negate both the input and the output:

Example:

function RoundHalfDown(num) {
  return -Math.round(-num);
}

document.write("1.5 rounds to ", RoundHalfDown(1.5), "<br>");
document.write("2.5 rounds to ", RoundHalfDown(2.5), "<br>");
document.write("2.4 rounds to ", RoundHalfDown(2.4), "<br>");
document.write("2.6 rounds to ", RoundHalfDown(2.6), "<br>");
document.write("-2.5 rounds to ", RoundHalfDown(-2.5), "<br>");
like image 139
Mark Dickinson Avatar answered Oct 02 '22 07:10

Mark Dickinson


do this:

var result = (num - Math.Floor(num)) > 0.5 ? Math.Round(num):Math.Floor(num);
like image 37
Ashraf Iqbal Avatar answered Oct 02 '22 07:10

Ashraf Iqbal