string to float,会丢失数据,所以大数就会丢掉数据,数越大,丢失的情况就越严重。
比如,
new Float(“123456789”) --》1.23456792E8, 只有前7位是准的,第8位是第九位四舍五入的效果,
new Float(“1234.56789”) --》1234.5679, 只有前7位是准的,第8位是第九位四舍五入的效果
new Float(“1234.56789123456789”) --》1234.5679, 只有前7位是准的,第8位是第九位四舍五入的效果,第8位以后小数的位全部丢失
new Float(“123456789123456789”) --》1.23456791E17,也就是 123456789100000000
原因是
public Float(String s) throws NumberFormatException {
// REMIND: this is inefficient
this(valueOf(s).floatValue());
}
public static Float valueOf(String s) throws NumberFormatException {
return new Float(FloatingDecimal.readJavaFormatString(s).floatValue());
}
FloatingDecimal.readJavaFormatString() has stored all digits from input string, but when FloatingDecimal.floatValue(), it only read 7 from integer part and 9 from decimal fraction part
static final int singleMaxDecimalDigits = 7;
static final int intDecimalDigits = 9;
in the last of floatValue(), it uses double to convert to float
double dValue = doubleValue();
return stickyRound( dValue )
source code --> http://www.docjar.com/html/api/sun/misc/FloatingDecimal.java.html
float只可以8个有效位,超过就会丢失精度。
下面一个问题
Float xx = 2.0f;
Float yy = 1.8f;
Float tt = xx - yy;
System.out.println("tttttt-----" + tt);
结果是: tttttt-----0.20000005
前7位是对的,但是最后一位不对,为什么不是0.2呢?
因为2.0f在内存中不是2.0000000,1.8f内存中不是1.80000000
浮点加减运算是用内存的位进行2进制加减
12.0f-11.9f=0.10000038
参考 http://www.blogjava.net/jelver/articles/340038.html
本文深入探讨了Float类型在Java中的精度限制及原因,通过具体示例说明了数值转换过程中的精度损失现象,并解释了浮点运算中出现的误差。
454

被折叠的 条评论
为什么被折叠?



