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?
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?
You're dividing by an long
type, so it will round down to 0
.
Use this instead:
float y=x/1000000000.0;
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)
float y=x/1000000000;
float y=(float)(int)(x/1000000000);
float y=(float)(int)(25782/1000000000);
float y=(float)0;
float y=0.0;
Int and long division always result in int and long.
at least operand in your calculation needs to be a float or double
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;