繁体   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