Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Double vs BigDecimal

Tags:

java

I'm looking at some code that was using a double variable to store the results of (360-359.9998779296875) which is 0.0001220703125. The double variable stores this as -1.220703125E-4. When I use a BigDecimal its stored as 0.0001220703125. Why does double store it as -1.220703125E-4?

like image 321
c12 Avatar asked Dec 18 '25 10:12

c12


1 Answers

I won't mention precision issues here but only the way the numbers get printed.

As explained in the 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."

Whereas 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

You can try this little program to check the various output formats and, in particular, the threshold at which the representation switches from standard notation to scientific notation is not the same in the two classes.

Output:

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

Code:

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);
}
like image 150
assylias Avatar answered Dec 21 '25 02:12

assylias