my dog learned polymorphism*
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


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Is there any way to convert an int to a float ?