Search code examples
javabigdecimaldecimalformat

Scientific notation with bigDecimals and decimalFormat


I'm trying to display fractional numbers in scientific notation format using bigdecimals and decimalFormat and this is what I came up with so far:

 BigDecimal a = new BigDecimal("0.000001");
 DecimalFormat df = new DecimalFormat("0.0###E0");
 System.out.println(df.format(a));

This program outputs "1.0E-4", and that's exactly what I want. Now if I set the bigDecimal to be "0.2222" for example, the output is 2.222E-1.

My question is: is there any way to prevent the scientific notation in this case so instead of 2.222E-1, the output should be 0.2222?


Solution

  • Try String.format with the g format specifier. Documentation is here.

    Here's some example code:

    import java.math.BigDecimal;
    
    public class BigDecTest {
        public static final void main(String[] args) {
            BigDecimal a = new BigDecimal("0.000001");
            System.out.println(String.format("%6.4G",a));
    
            BigDecimal b = new BigDecimal("0.2222" );
            System.out.println(String.format("%6.4G", b));
        }
    }
    

    It produces:

    1.000E-06
    0.2222