简体   繁体   English

将浮点数舍入为java中的下一个整数值

[英]round a floating-point number to the next integer value in java

how can i round up a floating point number to the next integer value in Java? 如何将浮点数舍入到Java中的下一个整数值? Suppose 假设

2.1 -->3 2.1 - > 3

3.001 -->4 3.001 - > 4

4.5 -->5 4.5 - > 5

7.9 -->8 7.9 - > 8

You should look at ceiling rounding up in java's math packages: Math.ceil 你应该看一下java的数学包中的上限:Math.ceil


EDIT: Added the javadoc for Math.ceil. 编辑:添加了Math.ceil的javadoc。 It may be worth reading all the method in Math. 可能值得阅读数学中的所有方法。

http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#ceil%28double%29 http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#ceil%28double%29

public static double ceil(double a)

Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer. 返回大于或等于参数且等于数学整数的最小(最接近负无穷大)double值。 Special cases: 特别案例:

  • If the argument value is already equal to a mathematical integer, then the result is the same as the argument. 如果参数值已经等于数学整数,则结果与参数相同。
  • If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument. 如果参数为NaN或无穷大或正零或负零,则结果与参数相同。
  • If the argument value is less than zero but greater than -1.0, then the result is negative zero. 如果参数值小于零但大于-1.0,则结果为负零。

Note that the value of Math.ceil(x) is exactly the value of -Math.floor(-x) . 请注意, Math.ceil(x)的值正好是-Math.floor(-x)的值。

try this 试试这个

float a = 4.5f;

int d = (int) Math.ceil(a);

System.out.println(d);

I had the same issue where I was still getting the smaller int value. 我有同样的问题,我仍然得到较小的int值。 It was the division, not the Math.ceil. 这是师,而不是Math.ceil。 You have to add a (float) cast to the ints. 你必须在int中添加一个(浮点)强制转换。 This is how I fixed it: 这就是我修复它的方法:

int totalNumberOfCachedData = 201;
int DataCountMax = 200;

float ceil =(float) totalNumberOfCachedData / (float)DataCountMax;
int roundInt = (int) Math.ceil(ceil);

This will give me 2 for the value of roundInt. 这将给我2 roundInt的值。

See 看到

float a=10.34f,b=45.678f;

System.out.println((int)Math.ceil(a));
System.out.println((int)Math.ceil(b));

Output 产量

11
46

I'm using this: 我正在使用这个:

public static int roundDoubleToUpperInt(double d){
    return (d%1==0.0f)?(int)d:(int)(d+1);
}

If it helps someone, here's how I get this working: 如果它对某人有帮助,这就是我的工作方式:

int arraySize = 3;
int pageSize = 10;
int pagesQty = (int) Math.ceil(arraySize / (float) pageSize);

System.out.println(pagesQty);

//Displays 1

Divisor must be a float in order to work properly. 除数必须是浮点才能正常工作。

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

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