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.
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);
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
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
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.
int RoundedUp = (int) Math.ceil(RandomReal);
This seemed to do the perfect job. Worked everytime.
Source: Stackoverflow.com