wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Is there any way to convert an int to a float ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Is there any way to convert an int to a float ?" Watch "Is there any way to convert an int to a float ?" New topic
Author

Is there any way to convert an int to a float ?

Anjanesh Lekshminarayanan
Ranch Hand

Joined: Oct 21, 2003
Posts: 46
Hi
Is there any way to convert an int to a float directly ?

int a=5;
int b=6;
System.out.println( what-do-to-here(a/b) );

Thanks


Anjanesh Lekshminarayanan
Prashanth Lingala
Ranch Hand

Joined: Nov 13, 2004
Posts: 66
class Conversion
{
public static void main(String[] args)
{
int a = 5;
int b = 6;
System.out.println((float)a/b);
}
}


Have A Nice Day !!!
Anjanesh Lekshminarayanan
Ranch Hand

Joined: Oct 21, 2003
Posts: 46
Thanks
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Note that (float)a/b = 0.8333333, but (float)(a/b) = 0.0.

In the first case, int a is cast as a float, which in turn causes b to be converted as well, since all operands are converted to the widest type (at least int) before the operation is performed.

But in the second case, the division is performed on ints, and the result --which is already truncated to an int -- is then cast to type float.
[ February 18, 2005: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Is there any way to convert an int to a float ?
 
Similar Threads
converting string to integer
doubt regarding division
Converting String value 2.0 into int
int to float conversion
Need to convert a float value into a normal value