information loss from long to float in Java

if you call the following method of Java

void processIt(long a) {
  float b = a;  /*do I have loss here*/
}

do I have information loss when I assign the long variable to the float variable?

The Java language Specification says that the float type is a supertype of long.

Jon Skeet
people
quotationmark

Do I have information loss when I assign the long variable to the float variable?

Potentially, yes. That should be fairly clear from the fact that long has 64 bits of information, whereas float has only 32.

More specifically, as float values get bigger, the gap between successive values becomes more than 1 - whereas with long, the gap between successive values is always 1.

As an example:

long x = 100000000L;
float f1 = (float) x;
float f2 = (float) (x + 1);
System.out.println(f1 == f2); // true

In other words, two different long values have the same nearest representation in float.

This isn't just true of float though - it can happen with double too. In that case the numbers have to be bigger (as double has more precision) but it's still potentially lossy.

Again, it's reasonably easy to see that it has to be lossy - even though both long and double are represented in 64 bits, there are obviously double values which can't be represented as long values (trivially, 0.5 is one such) which means there must be some long values which aren't exactly representable as double values.

people

See more on this question at Stackoverflow