Search code examples
javafloating-pointdoubledecimalexponential

Fomat float and double into scientific notation in specific format given below


I have already asked a question here and it was marked duplicate although it didn't solve my question and I tried to reopen but it got in vain. Forcing BigDecimals to use scientific notation

format decimal number to specific exponential format in java

So before marking my question duplicate please see that it is related to my problem.

Question :

Given a float or double number op into specific format eg : 13.33 = 0.1333 E+02 0.00023 = 0.23 E-03

The non zero digit of the number starts from just after the decimal.

How to use Decimal Format to achieve this output.


Solution

  • As you want the non zero digit of the number starts from just after the decimal.

    you can do

        BigDecimal x = new BigDecimal("13.33");
        DecimalFormat frmt = new DecimalFormat(".00E00");
        String formatted = "0" + frmt.format(x.doubleValue());
        System.out.println("result: " + formatted);
    

    results

    13.33
    result: 0.13E02
    0.00023
    result: 0.23E-03