简体   繁体   中英

Loss of precision in java

All integer literals are treated as int in java and floating point literals are treated as double in java. Then why does

    byte b =10;

does not give any error but

   float f = 10.0;

gives a loss of precision error when in both cases down-casting takes place?

In the case of int to byte , there's no real concern about a loss of precision , because both types have the same degree of granularity. You'll get an error if you try to convert a literal with a value outside the range of byte to byte . (The error message given in that case is slightly misleading.)

In the case of double to float , you can have a constant value which is in the right range , but still lose precision . In your specific case of 10.0, the value can be represented exactly in both float and double , but that's not the case in general.

As an example of that, consider this:

float f = (float) 10.1; // Or float f = 10.1f;
double d = 10.1;
System.out.println(f == d); // Prints false

That's because precision is being lost in the conversion from double to float - neither type can represent 10.1 exactly, but double gets close to it than float does. The == operator will mean f is converted back to a double , with a different value to d .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM