Search code examples
javabigdecimalexponential

bigdecimal subtraction results in exponential


I have the following code.

BigDecimal b1 = new BigDecimal("1.12345678912345678");
    BigDecimal b2 = new BigDecimal("1.12345678912345678");
    System.out.println(b1.subtract(b2));

The output is : 0E-17

How can I avoid the exponential format ? The method toPlainString of bigdecimal will return String and I do not want that. I want my bigdecimal object to be there without exponential value.


Solution

  • You are calling println(Object) method and it internally uses the Object.toString() method.

    And from the JavaDoc of BigDecimal.toString()

    Returns the string representation of this BigDecimal, using scientific notation if an exponent is needed.

    Your statement about toPlainString() method and wanting a bigdecimal object doesn't make sense, since the difference is only between the toString() method and toPlainString() method (Both of which return a string representation in different formats). You will in both cases have the same BigDecimal object. And the difference is only while printing.