Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login

# problem related to floats

Abhishek Reddy
Ranch Hand

Joined: Mar 28, 2006
Posts: 259
float i=0.7f;
if(i<0.7)
System.out.println("hello");
else
System.out.println("world");

the output of this code is hello
why not world???

Abhishek
Shaan Shar
Ranch Hand

Joined: Dec 27, 2005
Posts: 1249

Originally posted by Abhishek Reddy Chepyala:
float i=0.7f;
if(i<0.7)
System.out.println("hello");
else
System.out.println("world");

the output of this code is hello
why not world???

By default 0.7 is double. So the precision of Double is more then Float.

Try out this program.

You will have a clear view of the problem.

Hope this helps you out.

The Best way to predict your future is to create it - Every great individual common man
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
float i=0.7f; // in this case i holds an approximation to the literal 0.7f to the precision of a float

i<0.7 // The 0.7 here is a double literal and the comparison has to be done with doubles.

When the float value in i is promoted to a double no extra precision can be added to the value.

So you have (something like):

0.69999990000000 < 0.69999999999999 which is true.

My explanation is only an approximation to what happens, but I think it conveys an idea of why you get the "wrong" answer.
[ October 03, 2006: Message edited by: Barry Gaunt ]

Getting someone to think and try something out is much more useful than just telling them the answer.
Shaan Shar
Ranch Hand

Joined: Dec 27, 2005
Posts: 1249

So My explanations was correct Barry??
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Originally posted by Ankur Sharma:
So My explanations was correct Barry??

Your statement that a double has more precision than a float is correct. I think we were answering the question at the same time (I am a very slow two finger typer )

I agree. Here's the link: http://aspose.com/file-tools

subject: problem related to floats