NumberFormat Parse问题 [英] NumberFormat Parse Issue

查看:166
本文介绍了NumberFormat Parse问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对将字符串解析为Double时遇到的这个特殊'错误'感到很困惑。

I am quite confused about this peculiar 'error' I am getting when parsing a String to a Double.

我已经设置了 NumberFormat 属性和符号。

I've already set up the NumberFormat properties and symbols.

传递15位和2位小数的字符串时(例如 str = 333333333333333,33
并使用解析数字num = NumberFormat.parse(str)结果省略了数字。

When passing a String with 15 digits and 2 decimals (ex. str = "333333333333333,33") and parsing it with Number num = NumberFormat.parse(str) the result is omitting a digit.

num的实际值是 3.333333333333333E14

它似乎与Strings一起使用所有的1,2和4但是...

It seems to be working with Strings with all 1's, 2's and 4's though...

任何人都可以启发我吗?

Anyone can enlighten me?

干杯
恩里科

推荐答案

简短回答;由于圆错误

(double) 111111111111111.11 != (double) 111111111111111.1

(double) 333333333333333.33 == (double) 333333333333333.3

如果你想要更高的精度,请使用setParseBigDecimal,parse将返回一个BigDecimal。

If you want more precision, use setParseBigDecimal and parse will return a BigDecimal.

为什么会这样?这是因为你处于双倍精度的极限。 17个很好,因为它可以代表。 2是两倍,双倍存储2的权力,所有17个中的两个的所有权力,所以17个四分之一和17个八分之一是好的。

Why does this happen? This is because you are at the limit of the precision of double. The 17 ones is fine as it can just be represented. The 2's is just double this and as double stores powers of two, every power of two of all 17 ones, so 17 fours and 17 eights is fine.

然而,17三分之一需要多于两倍来代表值,最后一位被截断。类似地,17五,六和九也有舍入错误。

However, 17 threes takes one more bit than double has to represent the value and this last bit is truncated. Similarly 17 fives, sixes and nines also have rounding errors.

double[] ds = {
        111111111111111.11,
        222222222222222.22,
        333333333333333.33,
        444444444444444.44,
        555555555555555.55,
        666666666666666.66,
        777777777777777.77,
        888888888888888.88,
        999999999999999.99};
for (double d : ds) {
    System.out.println(d + " - " + new BigDecimal(d));
}

打印以下内容。 double 在打印前略微舍入,BigDecimal显示double代表的确切值。

prints the following. The double is rounded slightly before printing and the BigDecimal shows you the exact values the double represents.

1.1111111111111111E14 - 111111111111111.109375
2.2222222222222222E14 - 222222222222222.21875
3.333333333333333E14 - 333333333333333.3125
4.4444444444444444E14 - 444444444444444.4375
5.5555555555555556E14 - 555555555555555.5625
6.666666666666666E14 - 666666666666666.625
7.777777777777778E14 - 777777777777777.75
8.888888888888889E14 - 888888888888888.875
1.0E15 - 1000000000000000

这篇关于NumberFormat Parse问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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