Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Anjanesh Lekshminarayanan
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Prashanth Lingala
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Conversion
{
public static void main(String[] args)
{
int a = 5;
int b = 6;
System.out.println((float)a/b);
}
}
 
Anjanesh Lekshminarayanan
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic