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
This is not possible.
To convert an integer data type to float you can wrap the integer with float64() or float32.
The doubleValue() method of Java Float class returns a double value corresponding to this Float Object by widening the primitive values or in simple words by directly converting it to double via doubleValue() method .
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With