简体   繁体   English

Java 向上舍入任意数字

[英]Java Round up Any Number

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 ?我似乎无法找到我正在寻找的关于一个简单问题的答案:如何将任何数字四舍五入到最接近的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.例如,当数字是 0.2、0.7、0.2222、0.4324、0.99999 时,我希望结果为 1。

So far I have到目前为止我有

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

It doesn't seem to be doing the job, though.不过,它似乎并没有完成这项工作。

Math.ceil() is the correct function to call. Math.ceil()是正确的调用函数。 I'm guessing a is an int , which would make a / 100 perform integer arithmetic.我猜a是一个int ,它会使a / 100执行整数算术。 Try Math.ceil(a / 100.0) instead.试试Math.ceil(a / 100.0)代替。

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/yhT0lhttp://ideone.com/yhT0l

I don't know why you are dividing by 100 but here my assumption int a;我不知道你为什么要除以 100 但这里我的假设是int a;

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

or或者

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

This seemed to do the perfect job.这似乎做得很完美。 Worked everytime.每次都工作。

10 years later but that problem still caught me. 10 年后,这个问题仍然困扰着我。

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.因为结果a / 100结果是一个整数并且它被四舍五入所以 Math.ceil 不能做任何事情。

You have to avoid the rounded operation with this您必须避免使用此四舍五入操作

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

Now it works.现在它起作用了。

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));最简单的方法就是:您将收到一个浮点数或双精度数,并希望将其转换为最接近的System.out.println((int)Math.ceil(yourfloat)); ,然后只需执行System.out.println((int)Math.ceil(yourfloat)); it'll work perfectly它会完美地工作

Just another option.只是另一种选择。 Use basics of math:使用数学基础知识:

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

Assuming a as double and we need a rounded number with no decimal place .假设 a 为 double 并且我们需要一个没有小数位的四舍五入数字。 Use Math.round() function.使用 Math.round() 函数。
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM