没有强制转换,将double转换为long的最佳方法是什么?
例如:
double d = 394.000; long l = (new Double(d)).longValue(); System.out.println("double=" + d + ", long=" + l);
Jon Skeet.. 242
假设您对截断为零感到满意,那么只需投射:
double d = 1234.56; long x = (long) d; // x = 1234
这比通过包装类更快 - 更重要的是,它更具可读性.现在,如果您需要舍入而不是"始终为零",则需要稍微复杂的代码.
假设您对截断为零感到满意,那么只需投射:
double d = 1234.56; long x = (long) d; // x = 1234
这比通过包装类更快 - 更重要的是,它更具可读性.现在,如果您需要舍入而不是"始终为零",则需要稍微复杂的代码.
......这是不会截断的舍入方式.匆匆在Java API手册中查找:
double d = 1234.56; long x = Math.round(d);
首选方法应该是:
Double.valueOf(d).longValue()
从Double(Java Platform SE 7)文档:
Double.valueOf(d)
返回
Double
表示指定double
值的实例.如果Double
不需要新实例,则通常应优先使用此方法,而不是构造函数Double(double)
,因为此方法可能通过缓存频繁请求的值来显着提高空间和时间性能.
(new Double(d)).longValue()
内部只做一个演员,所以没有理由创建一个Double对象.
Guava Math库有一个专门用于将double转换为long的方法:
long DoubleMath.roundToLong(double x, RoundingMode mode)
您可以使用它java.math.RoundingMode
来指定舍入行为.
如果你强烈怀疑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()); }
你想要二进制转换吗?
double result = Double.longBitsToDouble(394.000d);