#47 – Numeric Conversions Through Casting

A conversion needs to happen when assigning a numeric value of one type to a variable of a different type.

Data values can be implicitly (automatically) converted whenever the conversion would not result in a loss of data.  This is possible if the target type has a wider range of types or greater precision than the source type.

Implicit conversion:

 int i = 12;
 long l = i;     // Implicit (int to long)
 float f = i;    // Implicit (int to float)
 double d = 4.2f;  // Implicit (float to double)

An explicit conversion is required when the conversion cannot be done without losing data.  These conversions require a cast operator that specifies the target type.

Explicit conversion:

 long l = 12;
 int i = l;        // Compiler error--can't implicitly convert
 int i = (int)l;     // Explicit (long to int)
 float f = 4.2f;
 i = (int)f;         // Explicit (float to int)
 double d = 4.2f;
 f = (float)d;       // Explicit (double to float)
Advertisements