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

JavaIntegerFloating PointRounding

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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 - Java

try this

float a = 4.5f;

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

System.out.println(d);

Solution 3 - Java

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 - Java

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 - Java

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.

Solution 6 - Java

I'm using this:

public static int roundDoubleToUpperInt(double d){
	return (d%1==0.0f)?(int)d:(int)(d+1);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionS.KView Question on Stackoverflow
Solution 1 - JavaStevenView Answer on Stackoverflow
Solution 2 - JavaJatinView Answer on Stackoverflow
Solution 3 - JavaJeffMeJonesView Answer on Stackoverflow
Solution 4 - JavaLionView Answer on Stackoverflow
Solution 5 - JavaPh0b0xView Answer on Stackoverflow
Solution 6 - JavanegstekView Answer on Stackoverflow