加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java往返String – > float – > String甚至(某些)值

发布时间:2020-12-15 01:05:59 所属栏目:Java 来源:网络整理
导读:参见英文答案 how does Java convert floats to strings????????????????????????????????????3个 正如许多地方(例如Why cant decimal numbers be represented exactly in binary?)所解释的那样,并非所有小数部分都可以表示为浮点值(例如存储在Java中的浮点

参见英文答案 > how does Java convert floats to strings????????????????????????????????????3个
正如许多地方(例如Why can’t decimal numbers be represented exactly in binary?)所解释的那样,并非所有小数部分都可以表示为浮点值(例如存储在Java中的浮点数中).

给出的典型示例是“0.2”.根据这个漂亮的IEEE 754 Converter,最接近0.2的浮点数约为0.20000000298023224,因此解析“0.2”作为浮点数应该产生这个结果.

但是,我注意到Java似乎能够做到这一点:

String number="0.2";
float f = Float.parseFloat(number);
System.out.println("Result of roundtrip String -> float -> String: "+f);

打印:

Result of roundtrip String -> float -> String: 0.2

Test on IDeone.com

Java如何知道我想要(舍入)输出“0.2”,而不是如上所述的精确输出“0.20000000298023224”?

Javadocs of Float.toString()试着解释一下:

How many digits must be printed for the fractional part of m or a?
There must be at least one digit to represent the fractional part,and
beyond that as many,but only as many,more digits as are needed to
uniquely distinguish the argument value from adjacent values of type
float.

不幸的是,这让我更加困惑.为什么“打印尽可能多的数字来唯一区分参数值”允许Java打印“0.2”?

理想情况下,答案也可以解释为什么选择此打印算法.这个例子是(一些)往返工作吗?还有其他动机吗?

最佳答案
输出的舍入不是因为某些打印算法.这是因为浮动的大小.如果你这样做:

String fs = "0.2";
double f = Float.parseFloat(fs);
System.out.println(f);

你得到:

0.20000000298023224

Test on Ideone.com

这清楚地表明字符串“0.2”被解析为0.20000000298023224,但浮点数据类型无法保持它,并将其四舍五入为0.2. double数据类型能够保存这些数据,因此,当您将其解析为float,但将其存储为double时,您将获得预期的输出.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读