Java Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we'll explore various methods to convert from double to long in Java.

2. Using Type Casting

Let's check a straightforward way to cast the double to long using the cast operator:

Assert.assertEquals(9999, (long) 9999.999);

Applying the (long) cast operator on a double value 9999.999 results in 9999.

This is a narrowing primitive conversion because we're losing precision. When a double is cast to a long, the result will remain the same, excluding the decimal point.

3. Using Double.longValue

Now, let's explore Double's built-in method longValue to convert a double to a long:

Assert.assertEquals(9999, Double.valueOf(9999.999).longValue());

As we can see, applying the longValue method on a double value 9999.999 yields 9999. Internally, the longValue method is performing a simple cast.

4. Using Math Methods

Finally, let's see how to convert a double to long using round, ceil, and floor methods from the Math class:

Let's first check Math.round. This yields a value closest to the argument:

Assert.assertEquals(9999, Math.round(9999.0));
Assert.assertEquals(9999, Math.round(9999.444));
Assert.assertEquals(10000, Math.round(9999.999));

Secondly, Math.ceil will yield the smallest value that is greater than or equal to the argument:

Assert.assertEquals(9999, Math.ceil(9999.0), 0);
Assert.assertEquals(10000, Math.ceil(9999.444), 0);
Assert.assertEquals(10000, Math.ceil(9999.999), 0);

On the other hand, Math.floor does just the opposite of Math.ceil. This returns the largest value that is less than or equal to the argument:

Assert.assertEquals(9999, Math.floor(9999.0), 0);
Assert.assertEquals(9999, Math.floor(9999.444), 0);
Assert.assertEquals(9999, Math.floor(9999.999), 0);

Note that both Math.ceil and Math.round return a double value, but in both cases, the value returned is equivalent to a long value.

5. Conclusion

In this article, we've discussed various methods to convert double to long in Java. It's advisable to have an understanding of how each method behaves before applying it to mission-critical code.

The complete source code for this tutorial is available over on GitHub.

Java bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
Comments are closed on this article!