Float returning 0.0 and not 0.05!

I'm quite new to Java - so I'm sure it might be a datatype issue or something else very simple, but:

float theResult = 50000 / 100000;
System.out.println(theResult);

I just checked and a float is representative of 1.40129846432481707e-45 to 3.40282346638528860e+38.  So I am a little baffeled by such a simple thing!

Andrew
LVL 1
rebiesAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

hongjunCommented:
try this

float theResult = 1.0 * (50000 / 100000);
hongjunCommented:
An integer divides by an integer will give you integer and so will result in integer 0.
0 when cast to float will give you 0.0.

To solve the problem, you need to multiply by a float (1.0) to give what you want.

hongjun

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
rebiesAuthor Commented:
hongjun:

Makes sense (a little bit), but when I try that code above I get "incompatible types".  it's telling me it found a double.

Andrew
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

rebiesAuthor Commented:
Even if I try casting the '1.0' as a float (I think thats what the following code does), I still get the result of "0.0"...

float theResult = (float) 1.0 * (50000 / 100000);

rebiesAuthor Commented:
Okay, thanks hongjun!  You helped me find the solution...

float theResult = (float) 50000 / (float) 100000;

So I'm just making sure to cast every number as a float before running the calculation.  This works!

Andrew
StillUnAwareCommented:
to use float You must explicitly say that the numbers You are working are also float so rewrite the division this way

float theResult = 50000f / 100000f;
System.out.println(theResult);

for that You may consider using double, it is more flexible.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.