本文介绍了Java如何将浮点数转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  float p = 1.15f; 
BigDecimal bdp = new BigDecimal(p);
float q = 1.1499999f;
float r = 1.14999999f;

System.out.println(p); //1.15
System.out.println(bdp); //1.14999997615814208984375
System.out.println(q); //1.1499999
System.out.println(r); //1.15

所以我明白p1.15的十进制值不能准确表示在二进制。

所以大的小数bdp输出对我来说是完全有意义的...这是浮点数的实际值。

问题1

当浮点p被转换回输出字符串(如1.15)时,这个四舍五入是怎么发生的(从内部1.149 .. 375值到1.15)?

它在文档中指定的位置? toString javadoc并没有真正的帮助(至少我)。

我在:

维基百科的IEEE 754文章给出了这个:
$ b

问题2

所以这似乎是Java / IEEE 754浮动应该如何工作?



我可以保证浮点/字符串转换/表示的准确性达到一定数量的数字(比如p和q),数字超过Java会做一些舍入显示(如r)?

感谢您的帮助。

从JLS开始,4.2.4。浮点运算:


Here's what I'm looking at:

float p=1.15f;
BigDecimal bdp=new BigDecimal(p);
float q=1.1499999f;
float r=1.14999999f;

System.out.println(p);   //1.15
System.out.println(bdp); //1.14999997615814208984375
System.out.println(q);   //1.1499999
System.out.println(r);   //1.15

So I understand that the decimal value of "p" 1.15 can't be represented exactly in binary.
And so the large big decimal "bdp" output makes perfect sense to me ... that's the actual value of the float.

Question 1
When the float "p" gets converted back to a string for output (as 1.15), how/where does that rounding occur (from the internal 1.149..375 value to 1.15)?

And where is it specified in the documentation? The toString javadoc doesn't really help (me at least).

I do see this in the language spec:

Wikipedia's IEEE 754 article gives this:

Question 2
So it seems that this is just how Java/IEEE 754 floats are supposed to work?

I get guaranteed accuracy of float/string conversion/representation up to a certain number of digits (like for "p" and "q"), and if that number of digits is exceeded Java will do some rounding for display (like for "r")?

Thanks for help.

解决方案

From the JLS, 4.2.4. Floating-Point Operations:

这篇关于Java如何将浮点数转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 02:55