We often need to convert a floating point number into integral number e.g. a double or float value 234.50d to long value 234L or 235L. There are couple of ways to convert a double value to long value in Java e.g. you can simply cast a double value to long or you can wrap a double value into
Double object and call it's
longValue() method, or using
Math.round() method to round floating point value into nearest integer. Te right way to covert a double value to a long in Java really depends upon what you want to do with floating point value. If you just want to truncate the double value to remove zero and take integer value, you can simply cast double to long. If you have Double object instead of double primitive type then you can also
Double.longValue() method, this doesn't do anything but just cast the double primitive wrapped inside Double object to long. It's clear from 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 nearest long, you can use Math.round() method, this will return a long value rounded up to nearest position, for example if double value is 100.5 then it will rounded to 101, while if it is less than that e.g. 100.1 then it will be rounded to just 100. In next section we will see detailed examples of these 3 ways to convert double to long in Java.