Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

When you convert a double to a long in Java, you may lose precision because long can only store whole number values, while double can store decimal values.

To convert a double to a long, you can use the Math.round() method, which rounds the double value to the nearest long. Here's an example:

import java.lang.Math;

...

double myDouble = 3.14;
long myLong = Math.round(myDouble);

In this example, the Math.round() method rounds the myDouble variable to the nearest whole number, which is 3, and assigns the result to the myLong variable.

Alternatively, you can also cast the double to a long, but be aware that this will truncate any decimal values and may result in data loss. Here's an example:

double myDouble = 3.14;
long myLong = (long) myDouble;

In this example, the (long) cast truncates the decimal value of 0.14, and assigns the result to the myLong variable, which will be 3.