Java Round up Any Number

JavaMathIntRounding

Java Problem Overview


I can't seem to find the answer I'm looking for regarding a simple question: how do I round up any number to the nearest int?

For example, whenever the number is 0.2, 0.7, 0.2222, 0.4324, 0.99999 I would want the outcome to be 1.

So far I have

int b = (int) Math.ceil(a / 100);

It doesn't seem to be doing the job, though.

Java Solutions


Solution 1 - Java

Math.ceil() is the correct function to call. I'm guessing a is an int, which would make a / 100 perform integer arithmetic. Try Math.ceil(a / 100.0) instead.

int a = 142;
System.out.println(a / 100);
System.out.println(Math.ceil(a / 100));
System.out.println(a / 100.0);
System.out.println(Math.ceil(a / 100.0));
System.out.println((int) Math.ceil(a / 100.0));

Outputs:

1
1.0
1.42
2.0
2

See http://ideone.com/yhT0l

Solution 2 - Java

I don't know why you are dividing by 100 but here my assumption int a;

int b = (int) Math.ceil( ((double)a) / 100);

or

int b = (int) Math.ceil( a / 100.0);

Solution 3 - Java

int RoundedUp = (int) Math.ceil(RandomReal);

This seemed to do the perfect job. Worked everytime.

Solution 4 - Java

10 years later but that problem still caught me.

So this is the answer to those that are too late as me.

This does not work

int b = (int) Math.ceil(a / 100);

Cause the result a / 100 turns out to be an integer and it's rounded so Math.ceil can't do anything about it.

You have to avoid the rounded operation with this

int b = (int) Math.ceil((float) a / 100);

Now it works.

Solution 5 - Java

The easiest way to do this is just: You will receive a float or double and want it to convert it to the closest round up then just do System.out.println((int)Math.ceil(yourfloat)); it'll work perfectly

Solution 6 - Java

Just another option. Use basics of math:

Math.ceil(p / K) is same as ((p-1) // K) + 1

Solution 7 - Java

Assuming a as double and we need a rounded number with no decimal place . Use Math.round() function.
This goes as my solution .

double a = 0.99999;
int rounded_a = (int)Math.round(a);
System.out.println("a:"+rounded_a );

Output : 
a: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
QuestionStevanicusView Question on Stackoverflow
Solution 1 - JavamoinudinView Answer on Stackoverflow
Solution 2 - Javauser467871View Answer on Stackoverflow
Solution 3 - JavaLiehan ElsView Answer on Stackoverflow
Solution 4 - JavaReginaldo RigoView Answer on Stackoverflow
Solution 5 - JavaLouieAdautoView Answer on Stackoverflow
Solution 6 - JavaomilusView Answer on Stackoverflow
Solution 7 - JavaAnkit ChauhanView Answer on Stackoverflow