Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a NumberFormat in Java that supports both an upper-case and a lower-case 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 tweak a NumberFormat to recognize both an upper- and lower-case E as the exponent separator? Is there a best work-around? Anything better than running toUpper() on the input first?

like image 362
Paul Jackson Avatar asked Dec 18 '12 02:12

Paul Jackson


1 Answers

The answer is "no", not directly.

Although using toUpperCase() directly on the input is a small coding overhead to pay for consistency, there is this 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 imbue case insensitivity to its implementation.

like image 85
Bohemian Avatar answered Oct 15 '22 22:10

Bohemian