Java 中 Long 到 Double 的转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3724830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Conversion from Long to Double in Java
提问by Harry
Is there any way to convert a Long
data type to Double
or double
?
有没有办法将Long
数据类型转换为Double
或double
?
For example, I need to convert 15552451L
to a double
data type.
例如,我需要转换15552451L
为double
数据类型。
回答by Jim Brissom
Simple casting?
简单的铸造?
double d = (double)15552451L;
回答by Joe Kearney
What do you mean by a long datetype?
长日期类型是什么意思?
You can cast a long to a double:
您可以将 long 转换为 double:
double d = (double) 15552451L;
回答by YoK
You could simply do :
你可以简单地做:
double d = (double)15552451L;
Or you could get double from Long object as :
或者你可以从 Long 对象获得 double 为:
Long l = new Long(15552451L);
double d = l.doubleValue();
回答by pvorb
Are you looking for the binary conversion?
您在寻找二进制转换吗?
double result = Double.longBitsToDouble(15552451L);
This will give you the double
with the same bit pattern as the long
literal.
这将为您double
提供与long
文字相同的位模式。
Binary or hexadecimal literals will come in handy, here. Here are some examples.
二进制或十六进制文字在这里会派上用场。这里有些例子。
double nan = Double.longBitsToDouble(0xfff0000000000001L);
double positiveInfinity = Double.longBitsToDouble(0x7ff0000000000000L);
double positiveInfinity = Double.longBitsToDouble(0xfff0000000000000L);
(See Double.longBitsToDouble(long))
(见Double.longBitsToDouble(long))
You also can get the long
back with
你也可以得到long
背面
long bits = Double.doubleToRawLongBits(Double.NaN);
回答by Vikas
You can try something like this:
你可以尝试这样的事情:
long x = somevalue;
double y = Double.longBitsToDouble(x);
回答by Manav Patadia
Long i = 1000000;
String s = i + "";
Double d = Double.parseDouble(s);
Float f = Float.parseFloat(s);
This way we can convert Long type to Double or Float or Int without any problem because it's easy to convert string value to Double or Float or Int.
这样我们就可以将 Long 类型转换为 Double 或 Float 或 Int 没有任何问题,因为将字符串值转换为 Double 或 Float 或 Int 很容易。
回答by Deep
As already mentioned, you can simply cast long to double. But be carefulwith long to double conversion because long to double is a narrowing conversionin java.
如前所述,您可以简单地将 long 转换为 double。但是要小心long 到 double 的转换,因为 long 到 double 是java 中的缩小转换。
从 double 类型到 long 类型的转换需要从 64 位浮点值到 64 位整数表示的非平凡转换。根据实际运行时值,信息可能会丢失。
e.g. following program will print 1 not 0
例如以下程序将打印 1 而不是 0
long number = 499999999000000001L;
double converted = (double) number;
System.out.println( number - (long) converted);
回答by spearkkk
I think it is good for you.
我认为这对你有好处。
BigDecimal.valueOf([LONG_VALUE]).doubleValue()
BigDecimal.valueOf([LONG_VALUE]).doubleValue()
How about this code? :D
这段代码怎么样?:D