Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get float value from integer in java [duplicate]

Tags:

java

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

like image 281
AKZap Avatar asked Dec 24 '12 11:12

AKZap


People also ask

Can you multiply float and int in Java?

This is not possible.

How do you convert integer to float?

To convert an integer data type to float you can wrap the integer with float64() or float32.

Can we convert float to double in Java?

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 .


2 Answers

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.

like image 192
Brian Agnew Avatar answered Sep 28 '22 00:09

Brian Agnew


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;
like image 36
Rahul Avatar answered Sep 27 '22 23:09

Rahul