0

Is it possible to have an obligatory sign in mantissa?

For example I would like to get 0.01 and 1040.3 formatted using the same DecimalFormat as: 1.00000e-002 and 1.040300e+003

At the moment I'm using:

DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.getDefault() );
otherSymbols.setDecimalSeparator('.');
otherSymbols.setExponentSeparator("e");

format="0.00000E000";
DecimalFormat formatter = new DecimalFormat(format, otherSymbols);

but this pattern fails to display '+' in mantissa.

Marcin Kawka
  • 277
  • 2
  • 9
  • 1
    possible duplicate of [Java DecimalFormat Scientific Notation Question](http://stackoverflow.com/questions/1213747/java-decimalformat-scientific-notation-question) – Jørgen R Dec 10 '14 at 09:44

1 Answers1

1

I don't think this is possible using DecimalFormat. However, you could use something like this:

public static void main(String[] args) {
    System.out.println(format(1040.3, "0.000000E000"));
}

public static String format(double number, String pattern) {
    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.getDefault());
    otherSymbols.setDecimalSeparator('.');
    otherSymbols.setExponentSeparator("e");

    DecimalFormat formatter = new DecimalFormat(pattern, otherSymbols);
    String res = formatter.format(number);
    int index = res.indexOf('e') + 1;
    if (res.charAt(index) != '-') {
        res = res.substring(0, index) + "+" + res.substring(index);
    }
    return res;
}

This results in the String you desired, 1.040300e+003.

pietv8x
  • 248
  • 1
  • 9