Java大双精度损失

时间:2013-11-27 18:54:01

标签: java double

 double lnumber = Math.pow(2, 1000);

打印1.0715086071862673E301

我尝试过的事情

我尝试使用BigDecimal Class扩展此数字:

 String strNumber = new BigDecimal(Double.toString(lnumber)).toPlainString();

这只是打印:

  

10715086071862673000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

我也尝试过使用DecimalFormat:

    DecimalFormat df = new DecimalFormat("#");
    df.setMaximumFractionDigits(0);
    String strNumber = String.valueOf(df.format(lnumber));

打印相同的东西:

  

10715086071862673000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

根据Wolfram Alpha的实际答案是

enter image description here

如何打印所有实际值?

2 个答案:

答案 0 :(得分:10)

你不能混合和匹配Math,原始类型和BigDecimal,如果你想要真正的精度,只需使用BigDecimal:

BigDecimal value = new BigDecimal(2);
System.out.println(value.pow(1000));

答案 1 :(得分:0)

如果要查看double的实际值,请使用BigDecimal(double)构造函数。 Double.toString(lnumber)进行四舍五入。

System.out.println(new BigDecimal((Math.pow(2, 1000))))输出10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

Math.pow(2,1000)在double中是完全可表示的,因为它是2的幂,在可表示的范围内。