Java Round up Any Number

2019-01-07 05:36发布

问题:

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.

回答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



回答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);


回答3:

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

This seemed to do the perfect job. Worked everytime.



回答4:

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