将double类型转换为long类型而不强制转换的最佳方法是什么?
例如:
double d = 394.000;
long l = (new Double(d)).longValue();
System.out.println("double=" + d + ", long=" + l);
将double类型转换为long类型而不强制转换的最佳方法是什么?
例如:
double d = 394.000;
long l = (new Double(d)).longValue();
System.out.println("double=" + d + ", long=" + l);
当前回答
首选的方法应该是:
Double.valueOf(d).longValue()
来自Double (Java Platform SE 7)文档:
Double.valueOf(d)
返回表示指定Double值的Double实例。 如果不需要新的Double实例,则应该使用此方法 通常优先于构造函数Double(Double), 因为这种方法很可能产生明显更好的空间和时间 缓存频繁请求值的性能。
其他回答
假设你对截断为0感到满意,只需强制转换:
double d = 1234.56;
long x = (long) d; // x = 1234
这将比使用包装器类更快——更重要的是,它更具可读性。现在,如果你需要舍入而不是“总是趋近于0”,你将需要稍微复杂一些的代码。
简单地说:
double d = 394.000;
long l = d * 1L;
... 这是舍入法,不会截断。赶紧在Java API手册里查了一下:
double d = 1234.56;
long x = Math.round(d); //1235
如果你强烈怀疑DOUBLE实际上是LONG,并且你想
1)将其EXACT值处理为LONG
2)当它不是LONG时抛出错误
你可以尝试这样做:
public class NumberUtils {
/**
* Convert a {@link Double} to a {@link Long}.
* Method is for {@link Double}s that are actually {@link Long}s and we just
* want to get a handle on it as one.
*/
public static long getDoubleAsLong(double specifiedNumber) {
Assert.isTrue(NumberUtils.isWhole(specifiedNumber));
Assert.isTrue(specifiedNumber <= Long.MAX_VALUE && specifiedNumber >= Long.MIN_VALUE);
// we already know its whole and in the Long range
return Double.valueOf(specifiedNumber).longValue();
}
public static boolean isWhole(double specifiedNumber) {
// http://stackoverflow.com/questions/15963895/how-to-check-if-a-double-value-has-no-decimal-part
return (specifiedNumber % 1 == 0);
}
}
Long是Double的子集,所以你可能会得到一些奇怪的结果,如果你不知情地尝试转换一个在Long范围之外的Double:
@Test
public void test() throws Exception {
// Confirm that LONG is a subset of DOUBLE, so numbers outside of the range can be problematic
Assert.isTrue(Long.MAX_VALUE < Double.MAX_VALUE);
Assert.isTrue(Long.MIN_VALUE > -Double.MAX_VALUE); // Not Double.MIN_VALUE => read the Javadocs, Double.MIN_VALUE is the smallest POSITIVE double, not the bottom of the range of values that Double can possible be
// Double.longValue() failure due to being out of range => results are the same even though I minus ten
System.out.println("Double.valueOf(Double.MAX_VALUE).longValue(): " + Double.valueOf(Double.MAX_VALUE).longValue());
System.out.println("Double.valueOf(Double.MAX_VALUE - 10).longValue(): " + Double.valueOf(Double.MAX_VALUE - 10).longValue());
// casting failure due to being out of range => results are the same even though I minus ten
System.out.println("(long) Double.valueOf(Double.MAX_VALUE): " + (long) Double.valueOf(Double.MAX_VALUE).doubleValue());
System.out.println("(long) Double.valueOf(Double.MAX_VALUE - 10).longValue(): " + (long) Double.valueOf(Double.MAX_VALUE - 10).doubleValue());
}
(new Double(d)). longvalue()在内部只执行强制转换,因此没有理由创建Double对象。