Beginners Programs :

Java Convert Double To Long – Examples

Java convert double to Long – We have different ways to convert a double value to a long value.

  1. Simple type conversion
  2. round()
  3. longValue()
  4. parseLong() and String methods, etc

Simple type conversion

In this, we just will convert the double type data to long type with explicit type casting. In this conversion, the value after the decimal point is truncated and the value before the decimal point is retained.

Example:

Output:

But this conversion is good only up to a 19 digit number because long can hold a value up to 9223372036854775807 only. So we should not give a double value bigger than this. For any double value bigger than this, the system will give this (9223372036854775807) value only.

Math.round()

If we want to round off the number to its nearest long based on the fractional value, we can use Math.round() before conversion.

Example:

Output:

This kind of direct conversion cannot be done from “Double” to “Long” object. So the following code is not valid.

Example:

longValue()

To convert a Double object to Long object this method is suitable. We should invoke this with a Double object. We have this method in the class Double.

As this is not a static method, we cannot call this using its class name like Double.longValue(). With the implicit auto-boxing,  a Double object is created with Double d=12345.34

Example:

Output:

Long.parseLong()

The parseLong() methods can convert a String to a long value. So we should convert the double value to String first. As parseLong() needs a String does contain only digits we should truncate the available string up to dot (decimal point).

If the dot is not available, then we will take the complete string. To truncate up to dot, we use the substring() method. The valueOf() of String converts the double value to String.

Example:

Output: