-1

I want to round up every double I get . I've searched and found Math.ceil but it is not working as I expected. For example :

Log.v("this", "" + Math.ceil(300 / 1000));-->returns 0 - expected 1 
Log.v("this",""+Math.ceil(100 / 1000));-->returns 0 - expected 1 
Log.v("this",""+Math.ceil(50 / 1000));-->returns 0 - expected 1 
Log.v("this",""+Math.ceil(700 / 1000));-->returns 0 - expected 1 
Log.v("this",""+Math.ceil(1000 / 1000)); -->this is ok
Log.v("this",""+Math.ceil(1020 / 1000));-->returns 1 - expected 2 

What should I do ?

weston
  • 54,145
  • 21
  • 145
  • 203
navidjons
  • 501
  • 4
  • 9
  • 15

2 Answers2

7

You are not rounding doubles, you are rounding integers!

When you do

700 / 1000

You are making an integer division (as both sides are integers!)

System.out.println(700/1000) == 0 //Well, you know what i mean.

You need to have a double, so you need to promote one of the two sides to a higher number (int -> double), so that the division is now for doubles:

700 / (double) 1000 == 0.7

Ceiling will then work properly.

Diego Martinoia
  • 4,592
  • 1
  • 17
  • 36
  • 2
    Casting with `(double)` is one way to do it. One can also simply add a decimal point or `d` suffix: `700 / 1000.0` or `700 / 1000d` will also work. – VGR Sep 25 '15 at 13:16
0

As you start with two integers and want to end up with an integer it is better to not do this via floating point math:

public static int integerDivideRoundUp(int numerator, int denominator)
{
    int q = numerator / denominator;
    int r = numerator % denominator;
    return r == 0 ? q : q + 1;
}

i.e. if there is no remainder in the divide, return the integer division result, otherwise return one more.

Here is a branchless verison based on this answer:

public static int integerDivideRoundUp(int numerator, int denominator)
{
    int q = numerator / denominator;
    int r = numerator % denominator;
    return q - (-r >> (Integer.SIZE - 1));
}

Usage:

Log.v("this", "" + integerDivideRoundUp(300, 1000));
Community
  • 1
  • 1
weston
  • 54,145
  • 21
  • 145
  • 203