Java Round up Any Number
Solution 1
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
Solution 2
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
int RoundedUp = (int) Math.ceil(RandomReal);
This seemed to do the perfect job. Worked everytime.
Solution 4
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.
Related videos on Youtube
Comments
-
Stevanicus over 2 years
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.
-
Jon Skeet over 13 yearsWhy are you dividing by 100 in your sample code?
-
Nikita Rybak over 13 yearsI bet your
a
has integer type. -
Chris Dennett over 13 yearsTell us what your inputs are, and your expected outputs.
-
Stevanicus over 13 yearsyea ur right a is an int... thanks for pointing that out. 100.0 sorted it for me.
-
Jay over 13 yearsI'm guessing what he wants is a/100 rounded up, but yeah, the question could use some clarification.
-
martijnn2008 almost 9 yearsNOTE: At this question better answers are provided.
-
-
L.Grillo over 8 yearsthis only if "a" is double
-
Codeversed over 7 years^^ "a" needs to be a double or cast a double.
-
dantiston about 7 years
a
is anint
in this example, and it works as suggested. When doingint / float
the result is afloat
, as demonstrated in the output. Try out the link. -
Mohamed23gharbi about 6 yearsThis is a wrong answer, as it is asked here to round UP if a=0.2 the result will be 0