Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

int to float conversion !

 
Salamina Daniel
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2823
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
M Iftikhar
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The voice conversation with Impulse has ended.
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Salamina Daniel
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic