在Java中从double转换为float [英] Converting from double to float in Java

查看:3784
本文介绍了在Java中从double转换为float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我正在使用 double ,并将其转换为 float ,那么这是如何工作的究竟?该值是否被截断,因此它适合浮点数?或者值的取值有所不同?对不起,如果这听起来有点补救,但是我试图把握 float double 转换的概念。 / p>

If I'm working with a double, and I convert it to a float, how does this work exactly? Does the value get truncated so it fits into a float? Or does the value get rounded differently? Sorry if this sounds a bit remedial, but I'm trying to grasp the concept of float and double conversions.

推荐答案

Java语言规范,第5.1.3节

From the Java Language Specification, section 5.1.3:


从double到float的缩小原语转换由IEEE 754舍入规则(§4.2.4)控制。此转换可能会失去精度,但也会失去范围,导致从非零双精度和浮动无穷大的浮点零有限双精度。双NaN转换为浮点数NaN,双重无限远转换为相同签名的浮点无穷大。

A narrowing primitive conversion from double to float is governed by the IEEE 754 rounding rules (§4.2.4). This conversion can lose precision, but also lose range, resulting in a float zero from a nonzero double and a float infinity from a finite double. A double NaN is converted to a float NaN and a double infinity is converted to the same-signed float infinity.

第4.2.4节说:


Java编程语言要求浮点算术的行为就好像每个浮点运算符将其浮点数结果舍入到结果精度一样。不精确的结果必须四舍五入到最接近无限精确结果的可表示值;如果两个最近的可表示值相等,则选择其最低有效位为零的值。这是IEEE 754标准的默认舍入模式,称为round to nearest。

The Java programming language requires that floating-point arithmetic behave as if every floating-point operator rounded its floating-point result to the result precision. Inexact results must be rounded to the representable value nearest to the infinitely precise result; if the two nearest representable values are equally near, the one with its least significant bit zero is chosen. This is the IEEE 754 standard's default rounding mode known as round to nearest.

这篇关于在Java中从double转换为float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆