Java rounding up to an int using Math.ceil

前端 未结 15 1691
陌清茗
陌清茗 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: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();
    

提交回复
热议问题