为什么0.1正确表示float? (我知道为什么不在2.0-1.9的结果中) [英] Why 0.1 represented in float correctly? (I know why not in result of 2.0-1.9)

查看:436
本文介绍了为什么0.1正确表示float? (我知道为什么不在2.0-1.9的结果中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我读了很多关于浮点数表示的内容(包括:如何在浮点算术和十进制中表示0.1)。
现在我明白0.1不能正确表示,当我这样做:

  System.out。 println(2.0f  -  1.9f); 

我永远不会得到确切的结果。

<所以问题是:
如何在下面的代码中表示0.1f以正确打印0.1?
是一种合成糖吗?
在我上面提到的那篇文章中说:0.1在内存中表示为0.100000001490116119384765625。所以为什么我没有得到这个代码输出:

$ p $ System.out.println(0.1f);

Java如何处理这个问题?

对浮点数和双精度执行一些舍入操作。它使用 Float.toString(),它本身(在oraclew JDK中)委托给 FloatingDecimal 类 - 你可以看看
FloatingDecimal#toJavaFormatString()
的来源

如果您尝试:

  BigDecimal bd = new BigDecimal(0.1f); 
System.out.println(bd);

你会看到0.1f的实际值:0.100000001490116119384765625。

I've read a lot about float representation recently (including this: How To Represent 0.1 In Floating Point Arithmetic And Decimal). Now I understand that 0.1 can't be represented correctly, and when I do this:

System.out.println(2.0f - 1.9f);

I'll never get precise result.

So the question is: How represented 0.1f in the following code in order to print 0.1 correctly? Is that some kind of syntatic sugar? In the article that I above mentioned says: 0.1 represented in memory as 0.100000001490116119384765625. So why I don't get this output for this code:

System.out.println(0.1f);

How does Java deal with this?

解决方案

System.out.println performs some rounding for floats and doubles. It uses Float.toString(), which itself (in the oraclew JDK) delegates to the FloatingDecimal class - you can have a look at the source of FloatingDecimal#toJavaFormatString() for gory details.

If you try:

BigDecimal bd = new BigDecimal(0.1f);
System.out.println(bd);

You will see the real value of 0.1f: 0.100000001490116119384765625.

这篇关于为什么0.1正确表示float? (我知道为什么不在2.0-1.9的结果中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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