Search code examples
javabigdecimal

Prevent conversion to exponent format in Java for Android while using BigDecimal


I am trying to divide 5 by 0.0005 using BigDecimal in Java in Android.

The result what I get is 1E+4 while i want to show 10000 as the result.

Right now what I am doing is :

BigDecimal aaaa = new BigDecimal("5");
BigDecimal bbbb = new BigDecimal("0.0005");

aaaa.divide( bbbb , new MathContext( 16, RoundingMode.DOWN) );

I want 16 digit precision with RoundingMode.DOWN

Scenerio 1 : Does not work as expected

aaaa = 5
bbbb = 0.0005
result => 1E+4
required => 10000

Scenerio 2 : Work as expected

aaaa = 100
bbbb = 3
result => 33.33333333333333
required => 33.33333333333333

Why there are different output format for both answers with exact same code. Is there a way to solve it?


Solution

  • It was simple. I got exactly what I want by using

    BigDecimal.stripTrailingZeros().toPlainString();
    

    This show output as I require without using DecimalFormat

    5 / 0.0005 => 10000 (and not in exponential format as => 1E+4)
    100 / 3    => 33.33333333333333