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

后端 未结 6 1255
广开言路
广开言路 2020-12-29 18:08

how can i round up a floating point number to the next integer value in Java? Suppose

2.1 -->3

3.001 -->4

4.5 -

相关标签:
6条回答
  • 2020-12-29 18:40

    You should look at ceiling rounding up in java's math packages: Math.ceil


    EDIT: Added the javadoc for Math.ceil. 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

    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. 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.
    • If the argument value is less than zero but greater than -1.0, then the result is negative zero.

    Note that the value of Math.ceil(x) is exactly the value of -Math.floor(-x).

    0 讨论(0)
  • 2020-12-29 18:40

    I had the same issue where I was still getting the smaller int value. It was the division, not the Math.ceil. You have to add a (float) cast to the ints. 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.

    0 讨论(0)
  • 2020-12-29 18:44

    I'm using this:

    public static int roundDoubleToUpperInt(double d){
        return (d%1==0.0f)?(int)d:(int)(d+1);
    }
    
    0 讨论(0)
  • 2020-12-29 18:45

    try this

    float a = 4.5f;
    
    int d = (int) Math.ceil(a);
    
    System.out.println(d);
    
    0 讨论(0)
  • 2020-12-29 18:48

    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
    
    0 讨论(0)
  • 2020-12-29 18:48

    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.

    0 讨论(0)
提交回复
热议问题