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

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


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);