如何在不强制转换的情况下将 double 转换为 long?

2022-01-12 00:00:00 type-conversion java

在不强制转换的情况下将 double 转换为 long 的最佳方法是什么?

What is the best way to convert a double to a long without casting?

例如:

double d = 394.000;
long l = (new Double(d)).longValue();
System.out.println("double=" + d + ", long=" + l);

推荐答案

假设您对截断为零感到满意,只需强制转换:

Assuming you're happy with truncating towards zero, just cast:

double d = 1234.56;
long x = (long) d; // x = 1234

这将比通过包装类更快 - 更重要的是,它更具可读性.现在,如果您需要始终接近零"以外的舍入,则需要稍微复杂一些的代码.

This will be faster than going via the wrapper classes - and more importantly, it's more readable. Now, if you need rounding other than "always towards zero" you'll need slightly more complicated code.

相关文章