0

Possible Duplicate:
Why does (360 / 24) / 60 = 0 … in Java

Having problems with floats and longs in Java

float f = 0.100f;
f = 3/180;

At the minute i am trying to do something like this with object and their attributes, but even to this simplest form my program returns 0.0.

I have tried this with Longs as well as still the same result. It's been a long day and maybe it's something simple but I'm at a brick wall.

Community
  • 1
  • 1
Melo1991
  • 375
  • 1
  • 3
  • 7

4 Answers4

7

Your expression 3/180 is performing an integer division, and it is then casting that into the float f. In integer division, 3/180 will return 0, and this is what you are seeing.

What you probably want to do is just add a decimal point to your numbers: f = 3.0/180.0;

Xymostech
  • 9,710
  • 3
  • 34
  • 44
  • Thank you all, as I said incredibly long day and my head is very very sore from banging it on the table. Again thanks to all that helped – Melo1991 Jan 30 '13 at 18:41
3

3/180 is integer division.
Therefore, the result is truncated to an integer.

You need to perform floating-point division: 3/180f

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
3

You do an integer division. So you get an int which is casted back to a float. Try this:

f = 3/180.0;

or

f = 3/180f;
rekire
  • 47,260
  • 30
  • 167
  • 264
3

Try 3.0/180. Otherwise, you are dividing two integers and you run into integer truncation. When you do integer division the result is also an integer, not a floating point number.

Oleksi
  • 12,947
  • 4
  • 56
  • 80
  • 1
    Please correct me but I think this is wrong. The second parameter is an int so you do an int division. – rekire Jan 30 '13 at 18:37
  • 1
    Java will automatically convert that second parameter to a floating point for the calculation because the first parameter is a float. For the computation to work, Java will do that for. You don't have to explicitly make both parameters floats, just one of them. – Oleksi Jan 30 '13 at 18:44
  • 1
    Thank you for your answer I really expected that this would fail. – rekire Jan 30 '13 at 18:46