Why does Java BigDecimal return 1E+1?

parkr picture parkr · May 29, 2009 · Viewed 18.5k times · Source

Why does this code sometimes return 1E+1 whilst for other inputs (e.g. 17) the output is not printed in scientific notation?

BigDecimal bigDecimal = BigDecimal.valueOf(doubleValue).multiply(BigDecimal.valueOf(100d)).stripTrailingZeros();
System.out.println("value: " + bigDecimal);

Answer

dfa picture dfa · May 29, 2009

use bigDecimal.toPlainString():

 BigDecimal bigDecimal = BigDecimal.valueOf(100000.0)
                     .multiply(BigDecimal.valueOf(100d))
                     .stripTrailingZeros();
 System.out.println("plain      : " + bigDecimal.toPlainString());
 System.out.println("scientific : " + bigDecimal.toEngineeringString());

outputs:

plain      : 10000000
scientific : 10E+6