Always Round UP a Double

前端 未结 7 1693
温柔的废话
温柔的废话 2020-12-06 09:55

How could I always round up a double to an int, and never round it down. I know of Math.round(double), but I want it to always round u

7条回答
  •  死守一世寂寞
    2020-12-06 10:12

    Short example without using Math.ceil().

    public double roundUp(double d){
        return d > (int)d ? (int)d + 1 : d;
    }
    

    Exaplanation: Compare operand to rounded down operand using typecast, if greater return rounded down argument + 1 (means round up) else unchanged operand.

    Example in Pseudocode

    double x = 3.01
    int roundDown = (int)x   // roundDown = 3
    if(x > roundDown)        // 3.01 > 3
        return roundDown + 1 // return 3.0 + 1.0 = 4.0
    else
        return x             // x equals roundDown
    

    Anyway you should use Math.ceil(). This is only meant to be a simple example of how you could do it by yourself.

提交回复
热议问题