Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round a double to closest even number

Tags:

java

math

I want to round a double value to the next even integer number. e.g.:

  • 489.5435 to 490
  • 2.7657 to 2

I've tried Math.rint(), but it gives me 489 instead of 490.

like image 896
Jannis Avatar asked Dec 05 '22 20:12

Jannis


1 Answers

Simply:

public static long roundEven(double d) {
    return Math.round(d / 2) * 2;
}

Gives:

System.out.println(roundEven(2.999));  // 2 
System.out.println(roundEven(3.001));  // 4 
like image 107
Jean Logeart Avatar answered Dec 22 '22 13:12

Jean Logeart