5

Possible Duplicate:
How can I convert integer into float in Java?

I got the problem with this code. I have two variable int i and float f.

int i = 23;

float f = i/10;

I suppose the value in f variable should be 2.3

but the real output value in f is 2.0

Why result occurred like this and how can i get the float value 2.3

Community
  • 1
  • 1
AKZap
  • 1,181
  • 6
  • 17
  • 31

5 Answers5

12

float f = i/10

is using integer arithmetic (both numerator and denominator are integers). The result is then promoted to a float type.

If you do

float f = i/10f

then you'll force floating point arithmetic (the denominator is now non-integer). The successive f indicates that 10f is treated as floating point. Specifying 10.0 or 10d would indicate a double.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
5

The output is 2.0f because both the numerator and denominator are integers hence it is using integer arithmetic.

i/10 returns 2 which when typecasted to float, converted to 2.0f.

You need to typecast atleast one of the num/denominators to float to make FP division

int i = 23;

float f = (float)i/10; 

or

float f = i/10f; 

Possible ways for this.

float z = (float) x / y;

or

float z = x / (float) y;

or(not required)

float z = (float) x / (float) y;
Rahul
  • 15,979
  • 4
  • 42
  • 63
0

please try instead of your i/10 use i/1Of

DRastislav
  • 1,892
  • 3
  • 26
  • 40
0

You can consider it as a 2 step operation

int i = 23;
int tmp = i/10;   
// tmp = 2
float f = (float) tmp;
// f = 2.0f

And this is how it looks like in bytecode

  L0         //int i = 23;
    BIPUSH 23
    ISTORE 1 // var 1 is 'i'
   L1        // int tmp = i/10;   
    ILOAD 1
    BIPUSH 10
    IDIV     // integer division 
    ISTORE 2 // var 2 - is tmp
   L2        // float f = (float) tmp;
    ILOAD 2
    I2F      // (float) tmp
    FSTORE 3 // var 3 is 'f'
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0
int i = 1;
float f = (float) i;
Ali Mohammadi
  • 1,306
  • 1
  • 14
  • 28