簡體   English   中英

java.text.DecimalFormat正前綴尾數

[英]java.text.DecimalFormat positive prefix mantissa

尾數是否可以有強制性標志?

例如,我想使用與以下相同的DecimalFormat獲取格式的0.01和1040.3:1.00000e-002和1.040300e + 003

目前,我正在使用:

DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.getDefault() );
otherSymbols.setDecimalSeparator('.');
otherSymbols.setExponentSeparator("e");

format="0.00000E000";
DecimalFormat formatter = new DecimalFormat(format, otherSymbols);

但是此模式無法在尾數中顯示“ +”。

我認為使用DecimalFormat不可能做到這一點。 但是,您可以使用以下方式:

public static void main(String[] args) {
    System.out.println(format(1040.3, "0.000000E000"));
}

public static String format(double number, String pattern) {
    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.getDefault());
    otherSymbols.setDecimalSeparator('.');
    otherSymbols.setExponentSeparator("e");

    DecimalFormat formatter = new DecimalFormat(pattern, otherSymbols);
    String res = formatter.format(number);
    int index = res.indexOf('e') + 1;
    if (res.charAt(index) != '-') {
        res = res.substring(0, index) + "+" + res.substring(index);
    }
    return res;
}

這將生成所需的字符串1.040300e + 003。

暫無
暫無

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

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