• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

float value ?  RSS feed

 
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need the float value of two values:

long a = 1;
int b = 2;
float a = b /a;

unfortunately, I get 0.0, instead of 0.5.

what should I do?
 
Author
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What have you tried? What might the issue be?
 
Ranch Hand
Posts: 160
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
do it like

float c = (float)a/b;

and don't forget to rad about the conversion of primitives in the numerical expression
 
David Newton
Author
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Manish: In general, we try to provide assistance and hints, not outright answers--particularly when it's something simple like this. It fosters an investigatory attitude and builds self-reliance.
 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Manish.


Using this:

float c = (float)a/b;

is obvious.

Done that before. But the point is, I have thought that JAVA 6 has the Autoboxing-Feature.

I guess, I read a little more..
 
David Newton
Author
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This doesn't have anything to do with autoboxing: autoboxing is the conversion/de-conversion between primitives and their object wrappers.
 
Sheriff
Posts: 21466
97
Chrome Eclipse IDE Java Spring Ubuntu VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
b / a is a long by int division, so the result is a long. For any mathematical operator, the following are the result types:
- if one of the operands is double -> double
- else if one of the operands is float -> float
- else if one of the operands is long -> long
- else int (never short, char or byte)
 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you! Now, I understand that:-)
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!