In this tutorial, you will learn how to convert a double
value to a long
in Java. We’ll explore explicit casting, handle potential precision loss, and demonstrate examples of rounding techniques for accurate results.
Java – Convert double to long
Converting double to long in Java – In Java, converting a double
to a long
requires explicit casting because double
is a floating-point type, while long
is an integer type. This conversion will truncate the decimal portion of the double
value, keeping only the whole number part.
Explicit Conversion from double to long
To convert a double
to a long
in Java, you need to use an explicit cast. This tells the compiler to truncate the decimal part and only keep the integer portion.
Example of Explicit Conversion
public class DoubleToLongExample {
public static void main(String[] args) {
double doubleVal = 9.99;
long longVal = (long) doubleVal; // Explicit conversion from double to long
System.out.println("Double value: " + doubleVal);
System.out.println("Long value after conversion: " + longVal);
}
}
Output
Double value: 9.99
Long value after conversion: 9
In this example, the double
value 9.99
is converted to a long
, resulting in 9
as the decimal portion is truncated.
Rounding Before Conversion
If you want to round the double
value to the nearest whole number before converting it to long
, you can use Math.round()
. This method rounds the double
value to the nearest whole number and returns a long
.
Example of Rounding Before Conversion
public class DoubleToLongExample {
public static void main(String[] args) {
double doubleVal = 9.99;
long longVal = Math.round(doubleVal); // Rounding and converting to long
System.out.println("Double value: " + doubleVal);
System.out.println("Long value after rounding: " + longVal);
}
}
Output
Double value: 9.99
Long value after rounding: 10
In this example, Math.round()
rounds 9.99
up to 10
before converting it to a long
.
Conclusion
Converting a double
to a long
in Java requires explicit casting, which truncates the decimal part. If you need to round the value, Math.round()
can provide the nearest whole number before conversion. Be cautious of potential precision loss due to truncation.