Float vs double (in Java)

Is there ever a case where these two methods return different values ​​for the same inputs?

int compare1(float a, float b)
{
    return Double.compare(a, b);
}

int compare2(float a, float b)
{
    return Float.compare(a, b);
}

Similarly, is it true (or false) that any number stored in java Float can be stored in java Double without loss of precision?

thank

+5
source share
3 answers

Yes; casting doubles to floats can give different results.

If the difference between aand is btoo small to be displayed in the float, it compare2()will return 0, then it compare1()will not.


You just edited a question to cancel what you requested. New answer:

I am pretty sure that they will always be the same.

+8
source
+4

A doublejust gives you more precision bits behind the decimal place than float. If all these extra bits are zero, you get the same value as the float. So yes, everything floatcan be converted to doublewithout loss of accuracy.

+1
source

All Articles