Java - 将双精度数转换为浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42109916/
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
Java - convert double to float
提问by 0ne_Up
I've seen an example where the following code is used to convert a double to a float:
我看过一个示例,其中使用以下代码将双精度数转换为浮点数:
Double.valueOf(someDouble).floatValue()
I would just do it like
我会这样做
(float)someDouble
Is there any advantage to using the former?
使用前者有什么好处吗?
回答by Eran
Looking at the implementation of Double
's floatValue()
:
查看Double
's的实现floatValue()
:
/**
* Returns the value of this {@code Double} as a {@code float}
* after a narrowing primitive conversion.
*
* @return the {@code double} value represented by this object
* converted to type {@code float}
* @jls 5.1.3 Narrowing Primitive Conversions
* @since JDK1.0
*/
public float floatValue() {
return (float)value;
}
It looks like it behaves exactly like your casting. Therefore there's no advantage to using it.
看起来它的行为与您的铸造完全一样。因此,使用它没有任何好处。