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

*Learn Spring*course, focused on the fundamentals of Spring 5 and Spring Boot 2:

**>> CHECK OUT THE COURSE**

Last modified: January 2, 2020

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

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.

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**.

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.

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.

## Leave a Reply