double to long Java

After knowing primitive data types and Java rules of Data Type Casting (Type Conversion), let us cast double to long.

By memory-wise, double and long both take 8 bytes of memory. Even then, a double value cannot be assigned to a long (here, rules of casting does not work) as double carries a mantissa (value after decimal point) where as long does not (it is a whole number). In explicit casting, mantissa part is truncated.

byte –> short –> int –> long –> float –> double

The left-side value can be assigned to any right-side value and is done implicitly. The reverse like short to byte requires explicit casting.

Examples of implicit casting

long x = 10;
double y = x;

byte x = 10;
int y = x;

Following program on double to long explains explicit casting, observe, Java style where a double is assigned to a long.

public class Conversions
{
  public static void main(String args[])
  {
    double d1 = 10.5;           // 8 bytes
    // long l1 = d1;              // error, double to long
          
    long l1 = (long) d1;       // data truncation, 0.5 gone

    System.out.println("double value: " + d1);   // prints 10.5
    System.out.println("Converted long value: " + l1);   // prints 10
     }
}


double to long
Output screenshot of double to long Java

long l1 = d1;

The above statement raises a compilation error "possible loss of precision".

long l1 = (long) d1;

The double d1 is explicitly type casted to long l1. Observe, the syntax of explicit casting. On both sides, it should be long only. When casted, the precision of 0.5 is lost (for this reason only, compiler does not compile). This is known as data truncation.

View all for 65 types of Conversions

Leave a Comment

Your email address will not be published.