1

Using Java i am getting a weird result

Double width = super.getWidth()/(32);
System.out.println(super.getWidth() + "  " + width);

prints 312 9.0

312/32 should be 9.75?

Allan Macmillan
  • 1,481
  • 3
  • 18
  • 30

3 Answers3

4

Assuming that super.getWidth() returns an integral type (an int, a long, etc.) the precision is lost during the division. When you divide a value of an integral type by an int, only the integer portion of the result is kept, while the fractional part is discarded.

Divide by 32.0 to fix the problem:

double width = super.getWidth()/32.0;
System.out.println(super.getWidth() + "  " + width);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

You need

Double width = super.getWidth()/(32.0);

When the java compiler comes across your original code, it sees two integers, and returns an integer. This way, it sees an integer and a double, therefore returning a double.

PlasmaPower
  • 1,864
  • 15
  • 18
1

Try

Double width = super.getWidth()/(32.0);
System.out.println(super.getWidth() + "  " + width);
Hugo Sousa
  • 1,904
  • 2
  • 15
  • 28
  • 1
    You should "try" answering the question, not just providing a fixed code snippet without explaining or even highlighting the change ;) – hyde Feb 28 '14 at 15:33