Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

problem related to floats

 
Abhishek Reddy
Ranch Hand
Posts: 259
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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???
 
Shaan Shar
Ranch Hand
Posts: 1249
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Shaan Shar
Ranch Hand
Posts: 1249
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So My explanations was correct Barry??
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 )
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic