Java convert double to Long – We have different ways to convert a double value to a long value or from long to double. Apart from the given program, you can check out the list of over 500+ Java programs with sample examples and outputs.
Methods we used to convert double to long/ long to double:
- Simple type conversion
- round()
- longValue()
- parseLong() and String methods, etc
Simple Double To Long
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:
1 2 3 4 5 |
double d1=2523.34, d2=12345e5; long l1=(long)d1, l2=(long)d2; System.out.println(l1+” “+l2); |
Output:
1 |
2523 1234500000 |
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:
1 2 3 4 5 |
double d1=2523.34, d2=2523.84; long l1=Math.round(d1), l2=Math.round(d2); System.out.println(l1+" "+l2); |
Output:
1 |
2523 2524 |
This kind of direct conversion cannot be done from “Double” to “Long” object. So the following code is not valid.
Example:
1 2 3 |
Double d=2523.34; Long l=(Long)d; //invalid |
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:
1 2 3 4 5 |
Double d=12345.34; Long l=d.longValue(); System.out.println(l); |
Output:
1 |
12345 |
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:
1 2 3 4 5 6 7 8 9 10 11 |
double d=12345.34; String s=String.valueOf(d); int i=s.indexOf('.'); s=s.substring(0, i==-1 ? s.length() : i); long l=Long.parseLong(s); System.out.println(l); |
Output:
1 |
12345 |