In Java, I am trying to get DecimalFormat to enforce the sign on an exponent sign. When it is positive I need a plus sign to appear. From what I have read this seems like a no brainer, but for myself it always throws up an error. I appreciate that there may be other methods to achieve my goal, but I would like to understand why in this specific method the error is occurring.
Double result = 123.456;
String sresult;
//This works
NumberFormat formatter = new DecimalFormat("0.00000E00");
sresult = formatter.format(result);
System.out.println(sresult); //1.23456E02
//This doesn't work
formatter = new DecimalFormat("0.00000E+00"); //Want to enforce the sign to appear
sresult = formatter.format(result);
System.out.println(sresult); //Expected 1.23456E+02 but error occurs
The error which is thrown up:
Exception in thread "main" java.lang.IllegalArgumentException:
Malformed exponential pattern "0.00000E+00"
at java.text.DecimalFormat.applyPattern(Unknown Source)
at java.text.DecimalFormat.(Unknown Source)
at deccheck.main(deccheck.java:13)
I appreciate any insight.
Thanks,
Mark
Easy way:
Outputs
1.23456E+02for your example.But I don’t believe there’s a way to do it from inside the
DecimalFormatpattern. Or at least the javadoc doesn’t indicate there is one.Edit: trashgod brings up a good point. You’d probably want to get positive and negative signs from
DecimalFormatSymbolsif you plan on localizing this to different regions.Edit 2: Andrei pointed out that
Eis also a localization variable. Shows what I know about localization.