Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

Members have full access to the forums. Advertisements are removed for registered users.

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

1. ## 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??

2. ## 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:

```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;```

3. ## The Following User Says Thank You to curmudgeon For This Useful Post:

bornacvitanic (August 31st, 2012)

4. ## 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!

5. ## Re: Why is in Java 9/2=4 ??

Originally Posted by curmudgeon
You're doing int division which always returns an int
I'm with you so far.

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.

```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:
```f1 =  1.999996000008, x1 =  1
f2 =  2.000004000008, x2 =  2
g1 = -1.999996000008, y1 = -1
g2 = -2.000004000008, y2 = -2```

Cheers!

Z

6. ## The Following 2 Users Say Thank You to Zaphod_b For This Useful Post:

bornacvitanic (August 31st, 2012), curmudgeon (August 31st, 2012)

7. ## Re: Why is in Java 9/2=4 ??

Thanks for the correction Z.