2

How will I round

  1. 1 < value < 1.5 to 1.5

  2. 1.5 < value < 2 to 2

skmaran.nr.iras
  • 8,152
  • 28
  • 81
  • 116

5 Answers5

8

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.

Andrew Mao
  • 35,740
  • 23
  • 143
  • 224
2
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

smk
  • 5,340
  • 5
  • 27
  • 41
1

Multiply by 2, use Math.ceil(), then divide that result by 2.

Gigatron
  • 1,995
  • 6
  • 20
  • 27
1
    public double round(double num)
    {
        double rounded = (int) (num + 0.4999f);
        if(num > rounded)
            return rounded + 0.5;
        else
            return rounded;
    }
Anthony Raimondo
  • 1,621
  • 2
  • 24
  • 40
-2

You can use

double numberGrade = 2.5;
Math.ceil(numberGrade);
Lynx777
  • 332
  • 1
  • 6
  • 17