File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Dividing floats Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Dividing floats" Watch "Dividing floats" New topic

Dividing floats

John Lynn

Joined: Dec 29, 2000
Posts: 15
Why would:

print out "2.0" instead of "2.6" ??
Rob Ross

Joined: Jan 07, 2002
Posts: 2205
a and b are both ints, so the division that is performed is an integer division, in which only the integer portion of the result is kept. After the integer division, the result is converted to a float and assigned to the left-hand-side variable.
If you want to use floating-point division, you can make your arguments (a&b) floats, or manually cast one of the operands to a float, like this:

float f = (float)a/b;
This will cause a to be converted to a float, and thus so will b, and the division will be a floating-point operation and maintain the non-integer portion of the result.

SCJP 1.4
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: Dividing floats