We often need to convert a floating-point number into an integral number e.g. a double or float value 234.50d to long value 234L or 235L. There are a couple of ways to convert a double value to a long value in Java e.g. you can simply cast a double value to long or you can wrap a double value into a Double object and call it's longValue() method, or using Math.round() method to round floating-point value to the nearest integer. The right way to convert a double value to a long in Java really depends on what you want to do with the floating-point value.
If you just want to truncate the double value to remove zero and take an integer value, you can simply cast double to long. If you have Double object instead of the double primitive type then you can also Double.longValue() method, this doesn't do anything but just cast the double primitive wrapped inside the Double object to long.
It's clear from the following code snippet taken from java.lang.Double class
On the other hand, if you want to round the double value to the nearest long, you can use the Math.round() method, this will return a long value rounded up to the nearest position.
It's clear from the following code snippet taken from java.lang.Double class
public long longValue() { return (long)value; }
On the other hand, if you want to round the double value to the nearest long, you can use the Math.round() method, this will return a long value rounded up to the nearest position.
For example, if the double value is 100.5 then it will be rounded to 101, while if it is less than that e.g. 100.1 then it will be rounded to just 100. In the next section, we will see detailed examples of these 3 ways to convert double to long in Java.
3 Examples to Convert Double to Long in Java
Here are three examples of converting a floating-point double value to long in Java. In our first example, we are using Double.longValue() to convert a double to long in Java. Here is the code :
well, here we have first converted a double primitive to a Double object and then called longValue() method on that.
double d = 129.00; long l = (new Double(d)).longValue(); //129
well, here we have first converted a double primitive to a Double object and then called longValue() method on that.
Apart from this example, I would not do that because longValue() does nothing but just cast the double value to long.
So if you have a primitive double, just directly cast it to long. Use this method only if you are getting a Double wrapper object. Here is the code example of casting a double to long in Java, you will notice in both cases result is the same.
Casting double to long just truncate trailing zero. This will be faster than going via the wrapper classes - and more importantly, it's more readable. Now, if you need rounding you can use Math.round() method to round a floating-point number into the nearest integral number
It doesn't give the same result as a cast. So it depends on double value, if the decimal point is 0.5 or greater then it will be rounded to the next long value otherwise to the previous or lower long value.
double d = 129.00; long v = (long) d; //129
Casting double to long just truncate trailing zero. This will be faster than going via the wrapper classes - and more importantly, it's more readable. Now, if you need rounding you can use Math.round() method to round a floating-point number into the nearest integral number
double d1 = 129.5; long v1 = Math.round(d1); //130 double d2 = 129.2; long v2 = Math.round(d2); //129
It doesn't give the same result as a cast. So it depends on double value, if the decimal point is 0.5 or greater then it will be rounded to the next long value otherwise to the previous or lower long value.
One more advantage of this method is that it works for wrapper classes Long and Double as well. You can use any of these methods to convert double to long in Java.
Double to Long Conversion in Java
Here is a complete example of converting a floating-point double value to an integral long value in Java. In this one program, we have used all three ways explained in the above paragraph. You can use this sample program to quickly run and check how it works.If you are using Eclipse IDE, just copy-paste the code and it will automatically create the correct Java source file and packages, provided you keep your mouse on a Java project.
/** * Java Program to show how to convert a floating point double * value to a long in Java. * * @author WINDOWS 8 */ public class DoubleToLong { public static void main(String args[]){ // first example - converting double to long using longValue() method double d = 102.9520; long l = (new Double(d)).longValue(); System.out.println("double value=" + d + ", long=" + l); // second example - rather simple just cast double to long double bill = 293.05; long myBill = (long) bill; System.out.println("double value=" + bill + ", long=" + myBill); // third example - rounding double value to long in Java double dbl = 3421.56; long rnd = Math.round(dbl); System.out.println("double value=" + dbl + ", long=" + rnd); } } Output double value=102.952, long=102 double value=293.05, long=293 double value=3421.56, long=3422This example shows different ways to convert double values to Long in Java.
Things to remember while converting Double to Long in Java
When converting a Double to a Long in Java, there are several important considerations to keep in mind to ensure accurate and expected results:
1. Loss of Precision
Be aware that converting a Double to a Long may result in a loss of precision. The fractional part of the Double will be truncated, and only the integer part will be retained.
2. Bounds Checking
Check whether the value falls within the valid range for a Long. The minimum and maximum values for a Long in Java are defined by Long.MIN_VALUE and Long.MAX_VALUE. If the Double value is outside this range, the conversion may lead to overflow or underflow.
3. Rounding
Understand that the conversion uses the longValue() method from the Number class, which rounds towards zero. This means that positive fractions will be rounded down, and negative fractions will be rounded up.
4. NaN and Infinite Values
Handle special cases like NaN (Not a Number) and infinite values (Double.POSITIVE_INFINITY and Double.NEGATIVE_INFINITY). Converting these special values to Long may result in Long.MIN_VALUE or Long.MAX_VALUE depending on the sign.
Here is another example illustrating these considerations:
public class DoubleToLongExample {
public static void main(String[] args) {
Double doubleValue = 1234.5678;
// Convert Double to Long
Long longValue = doubleValue.longValue();
System.out.println("Original Double value: " + doubleValue);
System.out.println("Converted Long value: " + longValue);
}
}
In this example, be cautious about the range of values that doubleValue can take and whether losing precision is acceptable for your specific use case. If more precision is required, consider using BigDecimal for arithmetic operations or converting to String before parsing as a Long.
That's all on how to convert a floating-point double value into long in Java. As I said, it's very easy to convert one data type to another in Java, and double and long is no different. In my opinion, you should just cast a double value too long if you are not interested in decimal value or just want to truncate the decimal part of a double value.
Instead of double primitive if you get Double object, then simply call Double.longValue() method, this will do the same as casting.
On the other hand, if you are interested in fraction values and want to round the floating-point value into nearest long then use Math.round() method, which will round up the double value into long.
Other Data Type conversion articles from Java67 blog
Other Data Type conversion articles from Java67 blog
- How to convert Array to String in Java (read here)
- How to convert util date to SQL date in JDBC (see here)
- Best way to Convert Numbers to String in Java (read here)
- How to convert Enum to String in Java (see here)
- How to convert String to Integer in Java (read here)
- How to convert decimal to binary numbers in Java (see here)
- Converting List to Set in Java (check here)
- How to convert hexadecimal to decimal, binary, and octal in Java (see here)
Since it Double you can also provide input in exponential format, for example
ReplyDeletelong input = new Double("2.9158614E7").longValue();
System.out.println(input);
It will work and return 29158614, cheers !!
My money is on valueOf() method becasue that cache some values and if you are dealing in lower ranges, you will see a performance boost.
ReplyDeleteConverting double to long is nothing but casting double value to long e.g.
ReplyDeletedouble d = (long) l;
ReplyDeletepublic class A {
public static void main (String args[]) {
String val = "20.30";
Float fAmount = 100* Float.valueOf(val);
long amount = fAmount.longValue();
System.out.println("Amount in Rp.:"+amount);
}
}
Console Ouptut:
Amount in Rp.:2029
The Float value is: 2029.9999 !