Round values ​​in java

How will i round

  • 1 <value <1.5 to 1.5

  • 1.5 <value <2 to 2

+1
source share
5 answers

What about

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

Since Math.ceil()double already returns, there is no need to share on 2.0dhere. This will work fine if you are in a range of integers that can be expressed as doubles without loss of precision, but be careful if you fall out of this range.

+7
source
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 pseudo code and should work

+2
source

2, Math.ceil(), 2.

+1
    public double round(double num)
    {
        double rounded = (int) (num + 0.4999f);
        if(num > rounded)
            return rounded + 0.5;
        else
            return rounded;
    }
+1

you can use

double numberGrade = 2.5;
Math.ceil(numberGrade);
-2
source

All Articles