Werner van Mook Werner van Mook - 3 months ago 6
Java Question

Why are the outcomes of the two calculations different?

I have the following two calculation using Math.round(...):

double x = 0.57145732;
x = x * 100;
x = Math.round(x * 10);
x = x / 10;


If I now print the value of x it will show me: 57.1.

double x = 0.57145732;
x = (Math.round((x * 100) * 10)) / 10;
// x = (Math.round(x * 1000)) / 10; //Also gives me 57.0.


If I now print the value of x it will show me: 57.0.

Why is there this difference in the outcome?

Answer

The Math.round() method returns an int (or long. Ole V.V corrected my mistake). Many people think that it returns float or double which gives rise to confusions as these.

In the second calculation,

Math.round((x * 100) * 10)

returns 571. Now, this value and 10 both are integers (571 is long, 10 is int). So when the calculation takes the form

x = 571 / 10

where x is double, 571/10 returns 57 instead of 57.1 since it is int. Then, 57 is converted to double and it becomes 57.0

If you do

x = (double)Math.round((x * 100) * 10) / 10.0;

its value becomes 57.1.


Edit: There are two versions of the Math.round() function. The one you used accepts a double (since x is double) and returns long. In this case, long and int make no difference though.