9

Here's an example:

Double d = (1/3);
System.out.println(d);

This returns 0, not 0.33333... as it should.

Does anyone know?

Motti
  • 99,411
  • 44
  • 178
  • 249
oletk
  • 105
  • 1
  • 1
  • 9
  • @ΦXocę웃Пepeúpaツ It isn't a duplicate. That question is a duplicate of this question. Look at the dates before you flag – Zoe Jul 16 '17 at 09:23

3 Answers3

38

That's because 1 and 3 are treated as integers when you don't specify otherwise, so 1/3 evaluates to the integer 0 which is then cast to the double 0. To fix it, try (1.0/3), or maybe 1D/3 to explicitly state that you're dealing with double values.

jjnguy
  • 128,890
  • 51
  • 289
  • 321
Firas Assaad
  • 22,872
  • 16
  • 57
  • 75
12

If you have ints that you want to divide using floating-point division, you'll have to cast the int to a double:

double d = (double)intValue1 / (double)intValue2

(Actually, only casting intValue2 should be enough to have the intValue1 be casted to double automatically, I believe.)

coobird
  • 151,986
  • 34
  • 204
  • 225
1

Use double and not Double unless you need to use these values in the object sense. Be aware about the Autoboxing concepts

Vijay Dev
  • 24,306
  • 20
  • 73
  • 96
  • The OP was asking about Java's truncation methods and why a division of integers is truncated, even if stored in a double; not about autoboxing. – ameed Jul 23 '13 at 03:59