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 int to float conversion ! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "int to float conversion !" Watch "int to float conversion !" New topic
Author

int to float conversion !

Salamina Daniel
Ranch Hand

Joined: Oct 10, 2001
Posts: 41
From what I know these are widening primitive conversions:
byte ->to short, int, long, float, or double
short ->to int, long, float, or double
char ->to int, long, float, or double
int ->to long, float, or double
long ->to float or double
float ->to double
I have tried :
class Testing {
public static void main(String[] args) {
int i = 1234567899;
float j = i;
System.out.println(i-(int)j);
}
}
Guess what : The output is -37
How this is happening ?
Paul Stevens
Ranch Hand

Joined: May 17, 2001
Posts: 2823
Here is your code with a couple of modifications:
class Testing {
public static void main(String[] args) {
int i = 1234567899;
float j = i;
System.out.println(i-j);
System.out.println(i);
System.out.println((int)j);
}
}
Notice what happens when you NARROW the conversion from float back to int.
M Iftikhar
Greenhorn

Joined: Oct 09, 2001
Posts: 3
int i = 1234567899;
float j = i; //float will convert the value 1234567940 0r 1.23456794E9
System.out.println(j);
// (int) j; this will convert the 1234567940 into 1234567930
// finally the result will be 12345678899 - 1234567930 = -31(approximately)
Basically the compiler will not convert the accurate value from float
to int because the this is explicit narrowing conversion evan though the
value is in the range.
that why you will get the unexpected result.


------------------
Iftikhar


Iftikhar
M Iftikhar
Greenhorn

Joined: Oct 09, 2001
Posts: 3
The voice conversation with Impulse has ended.
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
Consider that
System.out.println((float)1234567899);
prints
1.23456794E9
Note how the integer looses the last digits (precision) . This is because an integer can store numbers within a 32 bits range. While a float has only 24 bits for the mantisa.


SCJP2. Please Indent your code using UBB Code
Salamina Daniel
Ranch Hand

Joined: Oct 10, 2001
Posts: 41
Thanks for your answers.
From what I saw(by coding ) I conclude that is ok to say:
Widening conversion can result in loss of precision if an int or a long value is converted to float, or a long value to double !!
Anyone disagree ?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: int to float conversion !
 
Similar Threads
Which constructor?
Narrowing Problem
String / float Question
Unexpected class type. Encountering ClassCastException.
Casting int to long