Win a copy of Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications this week in the Java 9 forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# 'if' with float &double

nachiket deshpande
Ranch Hand
Posts: 114
hi all!
i have doubt in the following two simple if statements.please help
if(f*3.0F==1.0F)where f=1.0F/3.0F
returns true though the value of f is 0.33333...how come f*3.0F gives 1.0F
also
if(f*3.0==1.0)returns false?i can understand that f is promoted to double but why it i false
same with double
if(d*3.0==1.0)where d=1.0/3.0,
returns true even d is again 0.33333333333 how d*3.0 is 1.0?

sai challa
Ranch Hand
Posts: 54
Originally posted by nachiket deshpande:
hi all!
i have doubt in the following two simple if statements.please help
if(f*3.0F==1.0F)where f=1.0F/3.0F
returns true though the value of f is 0.33333...how come f*3.0F gives 1.0F
also
if(f*3.0==1.0)returns false?i can understand that f is promoted to double but why it i false
same with double
if(d*3.0==1.0)where d=1.0/3.0,
returns true even d is again 0.33333333333 how d*3.0 is 1.0?

I saw this piece of code on the sun's web site .I thought it might be of help to you.
class Test {
public static void main(String[] args) {
short s = 12; // narrow 12 to short
float f = s; // widen short to float
System.out.println("f=" + f);
char c = '\u0123';
long l = c; // widen char to long
System.out.println("l=0x" + Long.toString(l,16));
f = 1.23f;
double d = f; // widen float to double
System.out.println("d=" + d);
}
}
It produces the following output:
f=12.0
l=0x123
d=1.2300000190734863