This week's giveaway is in the Spring forum.
We're giving away four copies of Learn Spring Security (video course) and have Eugen Paraschiv on-line!
See this thread for details.
Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

casting from float to double gives undetermined result

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic