aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes problem related to floats Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "problem related to floats" Watch "problem related to floats" New topic
Author

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 ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
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
 
Similar Threads
use of quotes in type-in qts
print "hello world 101 times" , you should not use classes
hello
How to find index of a letter in a string?
100 times "hello world" without loop or recursive