Ask Your Question

How can I convert Double to Long in Java?

asked 2023-04-06 16:17:01 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2023-04-06 16:19:38 +0000

qstack gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer

Question Tools

1 follower


Asked: 2023-04-06 16:17:01 +0000

Seen: 15 times

Last updated: Apr 06 '23