0

When I have a fraction for example (5 / 6) then Java will just round this to 0.

For example:

System.out.println(1-(1/2));

This prints out 1 instead of 1/2 ie 0.5.

How can I tell Java that these should be floats or doubles instead of rounded to integers?

Alex
  • 627
  • 3
  • 12
  • 32
  • Most children learn integer division in primary school but many seem to forget it. In Java, C, C++ etc you need to use a floating point value (or cast) to say it is not an integer. – Peter Lawrey Jan 25 '15 at 09:01

1 Answers1

3

You explicitly use a double literal :

System.out.println(1-(1.0/2));

Or you cast one of the number to a double.

Eran
  • 387,369
  • 54
  • 702
  • 768