簡體   English   中英

如何在Java中創建同時支持大寫和小寫E作為指數分隔符的NumberFormat?

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

我有以下代碼:

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

產生以下輸出:

6.543E-4
6.543

有沒有辦法調整NumberFormat以將大寫和小寫E都識別為指數分隔符? 有最佳的解決方法嗎? 有什么比在輸入上先運行toUpper()更好的選擇?

答案是“否”,而不是直接。

盡管直接在輸入上使用toUpperCase()可以toUpperCase()一致性的少量編碼開銷,但是存在以下解決方法:

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

這是一個匿名類,它重寫parse()方法,以使其對其實現不區分大小寫。

至少Double.parseDouble都接受

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

輸出

6.543E-4
6.543E-4

至於NumberFormat我們可以將E更改為e

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

輸出

6.543E-4

但現在它不接受E :(

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM