rocketmanu
rocketmanu

Reputation: 137

About auto rounding result in java from double to integer?

The output of below code in Java is 3.0.

Why isn't it 3.3333333...?

double a = 10 / 3;
System.out.println(a);

Upvotes: 0

Views: 4779

Answers (1)

Bernhard Barker
Bernhard Barker

Reputation: 55619

Because int / int returns an int (regardless of what you assign it to afterwards).

So 10 / 3 returns 3 (integer division rounds down).

This would only then get converted to double.

To fix this, make one of the values a double (so it's double / int, which returns a double):

double a = 10.0 / 3;

or

double a = (double)10 / 3;

Upvotes: 7

Related Questions