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:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

# problem related to floats

Ranch Hand
Posts: 261
• Number of slices to send:
Optional 'thank-you' note:
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
• Number of slices to send:
Optional 'thank-you' note:

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
• Number of slices to send:
Optional 'thank-you' note:
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
• Number of slices to send:
Optional 'thank-you' note:
So My explanations was correct Barry??

Barry Gaunt
Ranch Hand
Posts: 7729
• Number of slices to send:
Optional 'thank-you' note:

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 )

 Consider Paul's rocket mass heater.