• Post Reply Bookmark Topic Watch Topic
  • New Topic

float value ?  RSS feed

 
nimo frey
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?
 
David Newton
Author
Rancher
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?
 
Manish Singh
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
Rancher
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
Rancher
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.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java 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!