gpt4 book ai didi

Java Double 与 BigDecimal

转载 作者:行者123 更新时间:2023-12-02 09:24:14 38 4
gpt4 key购买 nike

我正在查看一些使用 double 变量来存储 (360-359.9998779296875) 结果的代码,即 0.0001220703125。 double 变量将其存储为 -1.220703125E-4。当我使用 BigDecimal 时,它存储为 0.0001220703125。为什么将其双重存储为-1.220703125E-4?

最佳答案

我不会在这里提及精度问题,而只会提及数字的打印方式。

javadoc of Double#toString 中所述:

If m is less than 10^-3 or greater than or equal to 10^7, then it is represented in so-called "computerized scientific notation."

the javadoc of BigDecimal#toString :

If the scale is greater than or equal to zero and the adjusted exponent is greater than or equal to -6, the number will be converted to a character form without using exponential notation

您可以尝试这个小程序来检查各种输出格式,特别是,表示法从标准记数法切换到科学记数法的阈值在两个类中是不同的。

输出:

0.5                         0.5
3.0517578125E-5 0.000030517578125
9.5367431640625E-7 9.5367431640625E-7

代码:

public static void main(String args[]) {
//trying to use numbers with an exact double representation
double d1 = 0.5;
double d2 = 0.000030517578125;
double d3 = 0.00000095367431640625;

BigDecimal bd1 = new BigDecimal(d1);
BigDecimal bd2 = new BigDecimal(d2);
BigDecimal bd3 = new BigDecimal(d3);

System.out.println(d1 + "\t\t\t" + bd1);
System.out.println(d2 + "\t\t" + bd2);
System.out.println(d3 + "\t" + bd3);
}

关于Java Double 与 BigDecimal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12286064/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com