Java Round up Any Number

387,236

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

See http://ideone.com/yhT0l

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.

Share:
387,236

Related videos on Youtube

Stevanicus
Author by

Stevanicus

something boring goes here

Updated on September 05, 2021

Comments

  • Stevanicus
    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
      Jon Skeet over 13 years
      Why are you dividing by 100 in your sample code?
    • Nikita Rybak
      Nikita Rybak over 13 years
      I bet your a has integer type.
    • Chris Dennett
      Chris Dennett over 13 years
      Tell us what your inputs are, and your expected outputs.
    • Stevanicus
      Stevanicus over 13 years
      yea ur right a is an int... thanks for pointing that out. 100.0 sorted it for me.
    • Jay
      Jay over 13 years
      I'm guessing what he wants is a/100 rounded up, but yeah, the question could use some clarification.
    • martijnn2008
      martijnn2008 almost 9 years
      NOTE: At this question better answers are provided.
  • L.Grillo
    L.Grillo over 8 years
    this only if "a" is double
  • Codeversed
    Codeversed over 7 years
    ^^ "a" needs to be a double or cast a double.
  • dantiston
    dantiston about 7 years
    a is an int in this example, and it works as suggested. When doing int / float the result is a float, as demonstrated in the output. Try out the link.
  • Mohamed23gharbi
    Mohamed23gharbi about 6 years
    This is a wrong answer, as it is asked here to round UP if a=0.2 the result will be 0