# Why is in Java 9/2=4 ??

• August 31st, 2012, 06:15 AM
bornacvitanic
Why is in Java 9/2=4 ??
Every time I wanna divide 9 with 2 it prints out 4.0. Why not 4.5?? And how can i fix this??
• August 31st, 2012, 06:49 AM
curmudgeon
Re: Why is in Java 9/2=4 ??
You're doing int division which always returns an int (truncated to the nearest int). If you want a double result, you have to use at least one double in your statement:

Code :

```double result = 9.0 / 2; // the 9.0 makes this double math   // or this will work the same: result = 9 / 2.0;   // or this   result = (double) 9 / 2;```
• August 31st, 2012, 06:55 AM
bornacvitanic
Re: Why is in Java 9/2=4 ??
Tnx :) i tried it with doubles but it didnt work, but now i set all variables to double and it works!
• August 31st, 2012, 08:16 AM
Zaphod_b
Re: Why is in Java 9/2=4 ??
Quote:

Originally Posted by curmudgeon
You're doing int division which always returns an int

I'm with you so far.

Quote:

Originally Posted by curmudgeon
truncated to the nearest int

Actually it does not "truncate to the nearest int." It truncates by discarding any fractional part. Result is not necessarily the nearest int.

Code java:

```public class Z { public static void main(String [] args) { int x1 = 1000000/500001; int x2 = 1000000/499999; int y1 = -1000000/500001; int y2 = -1000000/499999; double f1 = (double)1000000/500001; double f2 = (double)1000000/499999; double g1 = -(double)1000000/500001; double g2 = -(double)1000000/499999; System.out.println("f1 = " + f1 + ", x1 = " + x1); System.out.println("f2 = " + f2 + ", x2 = " + x2); System.out.println("g1 = " + g1 + ", y1 = " + y1); System.out.println("g2 = " + g2 + ", y2 = " + y2); } }```

Output:
Code :

```f1 = 1.999996000008, x1 = 1 f2 = 2.000004000008, x2 = 2 g1 = -1.999996000008, y1 = -1 g2 = -2.000004000008, y2 = -2```

Cheers!

Z
• August 31st, 2012, 11:29 AM
curmudgeon
Re: Why is in Java 9/2=4 ??
Thanks for the correction Z.