Search code examples
javamathfractions

Is Java Contradicting Itself?


Should I declare Math.round(1/2) in Java to be an int or a double? If both are fine, which is more correct?

Also, why is it that Eclipse is telling me Math.round(1/2) = 0.0, while Math.round(0.5) = 1.0 ?

Any help would be appreciated!


Solution

  • The compiler starts by evaluating the expression 1/2. Both those numbers are integers, so it does integer math. In integers, 1 divided by 2 is 0. Then, it casts the 0 to a double in order to pass it to Math.round().

    If you want a correct answer, you need to pass in doubles: you can do this by using 1.0/2.0 instead of 1/2.