Search code examples
javacastingdoubleinteger-division

(Java) why is Math.ceil(15/10) is 1.0 and not 2.0?


Why is Math.ceil(15/10) 1.0 and not 2.0 ? When I run instead Math.ceil((double)15/10) I get 2.0 as expected.


Solution

  • Because dividing an integer by another integer gives you an integer : 15/10 is 1.

    From the specification :

    Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d · q| ≤ |n|. Moreover, q is positive when |n| ≥ |d| and n and d have the same sign, but q is negative when |n| ≥ |d| and n and d have opposite signs.

    You should use Math.ceil(15.0/10) or Math.ceil(15f/10) (the first one using doubles, the second one float).