how are the values determined in the following narrowing casts? Is float f truncated or rounded to an int first? or are the bit patterns just assigned.
Incorrect, I'm afraid. In both cases, the floating point number will be rounded to an integer (JLS 5.1.3). In the conversion to byte, the integer is subsequently truncated to a byte value. This two-step process can have remarkable side effects, for instanceThis printsThe explanation is left as an exercise for the reader It would be impossible to truncate a float to an int anyway - the representations are completely different, you don't get an int by simply slicing a few bits off a float. In fact int and float have the same number of bits (32). - Peter [This message has been edited by Peter den Haan (edited November 26, 2001).]
Jeff Gaer
Ranch Hand
Joined: Jun 04, 2001
Posts: 99
posted
0
public class IntTest { /** Creates new IntTest */ public IntTest() { } public static void main(String [] args){ double d=9.9; int i=(int)d; byte b=(byte)d; long l=(long)d; System.out.println( "int =["+i+"] byte=["+b+"] long=["+l+"]"); }
Did you read JLS 5.1.3? "... the floating-point value is rounded to an integer value V, rounding toward zero using IEEE 754 round-toward-zero mode."
JavaBeginnersFaq "Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Jeff Gaer
Ranch Hand
Joined: Jun 04, 2001
Posts: 99
posted
0
Think its my sloppy use of truncate. By truncate, I meant truncate the decimal part, which is effectively rounding towards 0. Not truncate as it probably should be interpreted, truncating the bits in the float. Thanks for the clarification.