简体   繁体   中英

Converting int/long zero to double

Considering this code snippet:

int i = 0;
double d1 = (double) i;
long l = 0L;
double d2 = (double) l;

Running this on my machine prints 0.0 for both conversions. But can d1 and d2 ever be anything but 0.0 ?

As I understand, this is a widening primitive conversion to which the spec says :

A widening primitive conversion does not lose information about the overall magnitude of a numeric value.

as well as

A widening conversion of an int or a long value to float, or of a long value to double, may result in loss of precision

As I understand the spec, the above would mean that int 0 will always become double 0.0 but long 0 can be converted to something else (eg 1E-20 or something like that). Is my spec interpretation correct?

The full quote is:

A widening conversion of an int or a long value to float, or of a long value to double, may result in loss of precision - that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode.

(Emphasis mine)

This is covering the case where the int / long value cannot be exactly represented in float / double (in which case, the nearest representable value is chosen). Clearly, 0 can be represented, so one would not expect a loss of precision.

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