File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes casting from float to double gives undetermined result Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "casting from float to double gives undetermined result" Watch "casting from float to double gives undetermined result" New topic
Author

casting from float to double gives undetermined result

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
public class test{

public static void main( String args[] ){
float A = 1.0F / 3.0F ;
double d=1.0 / 3.0 ;
1. System.out.println("d="+d);
2 System.out.println("before cast A= "+A);
//After casting
3 System.out.println("after cast A="+(double)A);
4 System.out.println("AA="+A*7.0);
5 System.out.println("AAA="+A*7.0F);
6 if( ( A * 7.0f == 1.0F )) System.out.println( "Equal" );
else System.out.println( "Not Equal" );
}
}
At line 3 when we type cast float to double ,few additional
digits are added to the result.See the diff in result at line 2 And line 3.But atually i feel this should not happen .Please anybody give me reason for that.
Ajith Kallambella
Sheriff

Joined: Mar 17, 2000
Posts: 5782
Double can hold higher precision values than float because of its size. Naturally the value of 1/3 stored as a double will hold more digits than 1/3 stored as a float. Hence the results are different!!
Ajith


Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
 
 
subject: casting from float to double gives undetermined result