java - 类型转换 long 以隐式 float 而不是缩小

标签 java casting implicit-conversion

在 java 中,隐式转换的层次结构是 byte -> short -> int -> long -> float -> double Long 可以容纳 8 个字节的数据。那么为什么它被隐式类型转换为只能容纳 4 个字节的 float 而不是可以容纳 8 个字节的 double。为什么它不被视为窄化?

哪些基本类型将被隐式转换为 char ?

最佳答案

这与使用了多少位数据无关。这是关于可以表示的规模。

来自 JLS section 5.1.2 (widening primitive conversions) :

A widening primitive conversion does not lose information about the overall magnitude of a numeric value.

...

A widening conversion of an int or a long value to float, or of a long value to double, may result in loss of precision - that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode (§4.2.4).

long的范围远小于float的范围,但精度固定为1。float的精度变化跨范围,就绝对值而言。换句话说,没有 long 超出 float范围,但有 long 值不能精确表示float值。

移动到 double 对此无济于事 - long 值也不能精确表示为 double

关于java - 类型转换 long 以隐式 float 而不是缩小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22067409/

相关文章:

java - 将unix time/utc转换为特定时区

java - ThreadDeath 上的线程生命周期

c++ - 将字符串从 Glib::ustring 转换为 double - gtkm 2

c# - AutoMapper:如何从 String 解析 Int 并可能根据数据类型创建规则?

scala - 寻找游戏中 Json 的隐含值

scala - 隐式类应该总是扩展 AnyVal 吗?

java - JRuby:启动浏览器时 Watir 挂起

java - java.util.Map 的通用测试工具?

c# - 将具体类转换为通用基接口(interface)

c - C 中的双指针常量正确性警告