How to create a NumberFormat in Java that supports both an upper-case and a lower-case E as an Exponent Separator?

六眼飞鱼酱① 提交于 2019-12-12 12:16:51

问题


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?


回答1:


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.




回答2:


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 :(



来源:https://stackoverflow.com/questions/13925334/how-to-create-a-numberformat-in-java-that-supports-both-an-upper-case-and-a-lowe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!