Always Round UP a Double

前端 未结 7 1688
温柔的废话
温柔的废话 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:24

    In simple words,

    • Math.ceil will always round UP or as said above, in excess.
    • Math.round will round up or down depending on the decimals.
      • If the decimal is equal or higher than 5, then it's rounded up.
        • decimal => 5. (1,5 = 2)
      • If the decimal is less than 5, then it's rounded down.
        • decimal < 5. (1,45 = 1)

    Examples of Math.ceil and Math.round:

    The code Below would return:
    Cost, without Ceil 2.2 and with Ceil 3 (int), 3.0 (double). If we round it: 2

        int m2 = 2200;
        double rate = 1000.0;
    
        int costceil = (int)Math.ceil(m2/rate);
        double costdouble = m2/rate;
        double costdoubleceil = Math.ceil(m2/rate);
        int costrounded = (int)Math.round(m2/rate);
        System.out.println("Cost, without Ceil "+costdouble+" and with Ceil "+
                costceil+"(int), "+costdoubleceil+"(double). If we round it: "+costrounded);
    

    If we change the value of m2 to for example 2499, the result would be: Cost, without Ceil 2.499 and with Ceil 3 (int), 3.0 (double). If we round it: 2
    If we change the value of m2 to for example 2550, the result would be:
    Cost, without Ceil 2.55 and with Ceil 3 (int), 3.0 (double). If we round it: 3

    Hope it helps. (Information extracted from previous answers, i just wanted to make it clearer).

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