Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round values in java

Tags:

java

rounding

How will I round

  1. 1 < value < 1.5 to 1.5

  2. 1.5 < value < 2 to 2

like image 598
Sarika.S Avatar asked Jul 18 '26 17:07

Sarika.S


2 Answers

How about

double rounded = Math.ceil(number * 2) / 2;

Since Math.ceil() already returns a double, no need to divide by 2.0d here. This will work fine as long as you're in the range of integers that can be expressed as doubles without losing precision, but beware if you fall out of that range.

like image 191
Andrew Mao Avatar answered Jul 20 '26 05:07

Andrew Mao


public double foo(double x){
  int res = Math.round(x);
  if(res>x) // x > .5
   return res -0.5;
  else 
   return res + 0.5;
}

I havent compiled this but this is pseudocode and should work

like image 37
smk Avatar answered Jul 20 '26 05:07

smk