Java rounding up to an int using Math.ceil

前端 未结 15 1665
陌清茗
陌清茗 2020-11-29 17:42
int total = (int) Math.ceil(157/32);

Why does it still return 4? 157/32 = 4.90625, I need to round up, I\'ve looked around and this se

相关标签:
15条回答
  • 2020-11-29 18:34

    There are two methods by which you can round up your double value.

    1. Math.ceil
    2. Math.floor

    If you want your answer 4.90625 as 4 then you should use Math.floor and if you want your answer 4.90625 as 5 then you can use Math.ceil

    You can refer following code for that.

    public class TestClass {
    
        public static void main(String[] args) {
            int floorValue = (int) Math.floor((double)157 / 32);
            int ceilValue = (int) Math.ceil((double)157 / 32);
            System.out.println("Floor: "+floorValue);
            System.out.println("Ceil: "+ceilValue);
    
        }
    
    }
    
    0 讨论(0)
  • 2020-11-29 18:36

    I know this is an old question but in my opinion, we have a better approach which is using BigDecimal to avoid precision loss. By the way, using this solution we have the possibility to use several rounding and scale strategies.

    final var dividend = BigDecimal.valueOf(157);
    final var divisor = BigDecimal.valueOf(32);
    final var result = dividend.divide(divisor, RoundingMode.CEILING).intValue();
    
    0 讨论(0)
  • 2020-11-29 18:37

    Check the solution below for your question:

    int total = (int) Math.ceil(157/32);
    

    Here you should multiply Numerator with 1.0, then it will give your answer.

    int total = (int) Math.ceil(157*1.0/32);
    
    0 讨论(0)
提交回复
热议问题