• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
reply
    Bookmark Topic Watch Topic
  • New Topic