Convert Double to Long in Java – 在Java中把双数转换成长数

最后修改: 2020年 1月 2日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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

在本教程中,我们将探讨在Java中从double转换为long的各种方法。

2. Using Type Casting

2.使用类型铸造

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

让我们检查一下使用cast操作符将double转换为long的直接方法。

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

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

在一个(long)值9999.999的double上应用(long)cast操作符,结果是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.

这是一个缩小的原始转换,因为我们正在失去精度。当一个double被投到一个long时,结果将保持不变,不包括小数点。

3. Using Double.longValue

3.使用Double.longValue

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

现在,让我们来探讨一下Double的内置方法longValue,将double转换成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.

正如我们所看到的,将longValue方法应用于double值9999.999,得到9999。在内部,longValue方法正在执行一个简单的转换

4. Using Math Methods

4.使用数学方法

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

最后,让我们看看如何使用Math类中的round, ceil, and floor方法将double转换为long

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

让我们先检查一下Math.round。这将产生一个最接近参数的值。

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:

其次,Math.ceil将产生大于或等于参数的最小值。

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:

另一方面,Math.floor的作用与Math.ceil>正好相反。这将返回小于或等于参数的最大值。

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.

请注意,Math.ceilMath.round都返回一个double值,但在这两种情况下,返回的值都相当于一个long值。

5. Conclusion

5.总结

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.

在这篇文章中,我们讨论了在Java中把double转换成long的各种方法。在将每个方法应用于关键任务代码之前,最好对每个方法的行为方式有所了解。

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

本教程的完整源代码可在GitHub上找到