How to create a NumberFormat in Java that supports both uppercase and lowercase E as an Exponent Separator?

I have the following code:

NumberFormat numberInstance = NumberFormat.getNumberInstance(); System.out.println(numberInstance.parse("6.543E-4")); System.out.println(numberInstance.parse("6.543e-4")); 

which produces the following output:

 6.543E-4 6.543 

Is there a way to set NumberFormat to recognize both upper and lower case E as an exponent delimiter? Have a better job? Anything better than running toUpper () on input first?

+4
source share
2 answers

The answer is no, not directly.

Although using toUpperCase() directly at the input is a small coding overhead to pay for consistency, this is a workaround:

 NumberFormat numberInstance = new NumberFormat() { @Override public Number parse(String str) { return super.parse(str.toUpperCase()); } }; 

This is an anonymous class that overrides the parse() method to implement insensitivity to its implementation.

+6
source

At least Double.parseDouble accepts both

  System.out.println(Double.parseDouble("6.543e-4")); System.out.println(Double.parseDouble("6.543E-4")); 

Output

 6.543E-4 6.543E-4 

as for NumberFormat, we can change E to e as

  DecimalFormat nf = (DecimalFormat)NumberFormat.getNumberInstance(); DecimalFormatSymbols s = new DecimalFormatSymbols(); s.setExponentSeparator("e"); nf.setDecimalFormatSymbols(s); System.out.println(nf.parse("6,543e-4")); 

Output

 6.543E-4 

but now it does not accept E :(

0
source

All Articles