精确地从字符串分配浮点数 [英] Assign to Float from string with precision
本文介绍了精确地从字符串分配浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
String s1 = 525.880005\" ;
Float f = new Float(s1);
System.out.println(f);
输出:
5.88
预期产出:
525.880005
解决方案
Float
只有7-8个有效数字。你的例子中的5是第9位数字。
即使它有足够的精度,我也不知道525.880005是否可以完全表示为二进制浮点数。如果精确的十进制表示对你很重要,你应该使用 BigDecimal
。
I have the following code, I want to assign a decimal value to float without losing precision.
String s1= "525.880005";
Float f = new Float(s1);
System.out.println(f);
Output: 5.88
Expected Output: 525.880005
解决方案
Float
only has 7-8 significant digits of precision. The "5" in your example is the 9th digit.
Even if it had enough precision, I don't know whether 525.880005 is exactly representable as a binary floating point number. Most decimal values aren't :)
You should use BigDecimal
if the exact decimal representation is important to you.
这篇关于精确地从字符串分配浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文