• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

problem related to floats

 
Ranch Hand
Posts: 261
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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???
 
Ranch Hand
Posts: 1252
Spring Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 1252
Spring Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So My explanations was correct Barry??
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 )
 
reply
    Bookmark Topic Watch Topic
  • New Topic