0

I have the following java code

long x=25782

float y=x/1000000000

Instead of y being equal to 0.000025782 as I would expect, it is equals 0.0

What am I doing wrong?

coolblue2000
  • 3,796
  • 10
  • 41
  • 62
  • 1
    http://stackoverflow.com/questions/10455677/division-in-java-always-results-in-zero-0?rq=1 – devnull May 07 '14 at 13:12
  • 3
    How did you get 396 rep on this site if you're asking questions that can be answered with 3 seconds of googling? – Paul Tomblin May 07 '14 at 13:12
  • 1
    @PaulTomblin 1) Uncalled for scathing remark; 2) You know as well as everybody else games can be *gamed* and in many respects StackOverflow fails to promote value especially when a lot of marginally good answers to bad questions gets you further than one good answer to a very good question... in the same amount of time. – Mihai Stancu May 07 '14 at 13:15
  • 1
    @PaulTomblin I'm not saying (by any means) that you should overlook the fact that this is a bad (duplicate) question. By all means, down-vote and vote-to-close to your heart' desire, that's what the buttons are there for. Just don't make the entire experience more unpleasant that it needs to be. – Mihai Stancu May 07 '14 at 13:18
  • @PaulTomblin perhaps if points gained from closed questions will would be retracted, people wouldn't struggle to answer an obvious duplicate question by googling for it and finding it... where else... on StackOverflow. – Mihai Stancu May 07 '14 at 13:19

4 Answers4

5

You're dividing by an long type, so it will round down to 0.

Use this instead:

float y=x/1000000000.0;
AntonH
  • 6,359
  • 2
  • 30
  • 40
1

Integer division gives an integer result

This is integer division; in integer division the answer is always an integer (by truncating the non integer part, not be rounding). Which you are then casting to a float.

The easiest solution is to include at least 1 float. So

long x=25782

float y=x/1000000000f //(or 1000000000.0) 

What you are effectively doing

float y=x/1000000000;
float y=(float)(int)(x/1000000000);
float y=(float)(int)(25782/1000000000);
float y=(float)0;
float y=0.0;
Richard Tingle
  • 16,906
  • 5
  • 52
  • 77
0

Int and long division always result in int and long.

at least operand in your calculation needs to be a float or double

Leon
  • 12,013
  • 5
  • 36
  • 59
0

You have an integer division, which will round to the right of the decimal point, as integer division gives integer result.

You should cast x to float.

Try:

float y=(float)x/1000000000;
laaposto
  • 11,835
  • 15
  • 54
  • 71