round a floating-point number to the next integer value in java

98,269

Solution 1

You should look at ceiling rounding up in java's math packages: Math.ceil


EDIT: Added the javadoc for Math.ceil. It may be worth reading all the method in Math.

http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#ceil%28double%29

public static double ceil(double a)

Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer. Special cases:

  • If the argument value is already equal to a mathematical integer, then the result is the same as the argument.
  • If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.
  • If the argument value is less than zero but greater than -1.0, then the result is negative zero.

Note that the value of Math.ceil(x) is exactly the value of -Math.floor(-x).

Solution 2

try this

float a = 4.5f;

int d = (int) Math.ceil(a);

System.out.println(d);

Solution 3

I had the same issue where I was still getting the smaller int value. It was the division, not the Math.ceil. You have to add a (float) cast to the ints. This is how I fixed it:

int totalNumberOfCachedData = 201;
int DataCountMax = 200;

float ceil =(float) totalNumberOfCachedData / (float)DataCountMax;
int roundInt = (int) Math.ceil(ceil);

This will give me 2 for the value of roundInt.

Solution 4

See

float a=10.34f,b=45.678f;

System.out.println((int)Math.ceil(a));
System.out.println((int)Math.ceil(b));

Output

11
46

Solution 5

If it helps someone, here's how I get this working:

int arraySize = 3;
int pageSize = 10;
int pagesQty = (int) Math.ceil(arraySize / (float) pageSize);

System.out.println(pagesQty);

//Displays 1

Divisor must be a float in order to work properly.

Share:
98,269
S.K
Author by

S.K

Updated on March 10, 2020

Comments

  • S.K
    S.K about 4 years

    how can i round up a floating point number to the next integer value in Java? Suppose

    2.1 -->3

    3.001 -->4

    4.5 -->5

    7.9 -->8