java - 为什么我可以将 float 传递给 Double 的构造函数?

标签 java floating-point double

在下面的代码中,我从doublefloatString 构造了一些Double 变量。但是,根据文档,Double 仅具有接受 doubleString 的构造函数 - 而不是 float。那么这段代码如何编译呢?

Double d1 = new Double(2.5);
Double d2 = new Double(2.5f); //Why can I pass a float here?
Double d3 = new Double("2.5");

最佳答案

因为 float 通常可以转换为 double 而不会丢失精度,所以 float 可以自动加宽double。参见 Widening Primitive Conversion有关 Java 将自动扩展哪些类型的信息。

有关float/double 转换的链接文档中指出了一个异常:

A widening primitive conversion from float to double that is not strictfp may lose information about the overall magnitude of the converted value.

关于java - 为什么我可以将 float 传递给 Double 的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51053086/

相关文章:

ios - 无法将类型 'String?' 的值分配给类型 'Double' 错误

java - 当用户输入小数点时,如何错误处理代码以防止程序崩溃?

c# - 在 .NET 中将 double 转换为 string 不如 C++ 精确?

java - android ImageView 内存不足错误

java - 基本练习应用程序输出。 java

casting - 所有 32 位 float 都精确表示为 f64 吗?

floating-point - 使用 flocq 定义 float 和证明

java - 当我为 JFrame 使用 FlowLayout 时,为什么我的图像没有出现?

Javafx - 如何访问 FXML "objects"

java - 从文件路径初始化对象变量