本文介绍了为什么Double.parseDouble使9999999999999999到10000000000000000?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么Double.parseDouble使 9999999999999999 10000000000000000
例如:

why is the Double.parseDouble making 9999999999999999 to 10000000000000000 ?For Example :

Double d =Double.parseDouble("9999999999999999");
String b= new DecimalFormat("#.##").format(d);
System.out.println(b);

IS打印

10000000000000000

相反,它必须显示 9999999999999999 9999999999999999.00

非常感谢任何帮助。

推荐答案

double 只有15/16位数的精度,当你给它一个数字,它不能代表(大部分时间甚至0.1都不准确)它需要最接近的代表性数字。

double only has 15/16 digits of accuracy and when you give it a number it can't represent (which is most of the time, even 0.1 is not accurate) it takes the closest representable number.

如果要代表 9999999999999999 确切地说,你需要使用BigDecimal。

If you want to represent 9999999999999999 exactly, you need to use BigDecimal.

BigDecimal bd = new BigDecimal("9999999999999999");
System.out.println(new DecimalFormat("#.##").format(bd));

打印

9999999999999999

很少有真实世界的问题需要这个准确性,因为你无法测量任何东西无论如何即每1万分之一的错误。

Very few real world problems need this accuracy because you can't measure anything this accurately anyway. i.e. to an error of 1 part per quintillion.

您可以使用

// search all the powers of 2 until  (x + 1) - x != 1
for (long l = 1; l > 0; l <<= 1) {
    double d0 = l;
    double d1 = l + 1;
    if (d1 - d0 != 1) {
        System.out.println("Cannot represent " + (l + 1) + " was " + d1);
        break;
    }
}

打印

Cannot represent 9007199254740993 was 9.007199254740992E15

最大可代表整数为9007199254740992,因为它需要少一点(作为它的偶数)

The largest representable integer is 9007199254740992 as it needs one less bit (as its even)

这篇关于为什么Double.parseDouble使9999999999999999到10000000000000000?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 03:48