如何使用指数表示法将double转换为n字符串?

时间:2015-06-07 16:57:20

标签: java string formatting double

我已经多次在SO上发现这种情况,但从来没有像我想要的那样。

我想将double转换为一个字符串,该字符串占用完全 n个字符。

如果n是例如6,那么


1,000,123.456将变为1.00E6
-1,000,123.456将变为1.0E-6
1.2345678将成为1.2345
1,000,000,000,000将成为1.0E12

我如何实现这一目标? 问候, Claas M。

P.S如何在SO上设置标签?

1 个答案:

答案 0 :(得分:1)

如果您将指数分量限制为E0到E99(正指数)和E0到E-9(负指数),您可以使用DecimalFormat和Regex的组合将结果格式化为6字符的长度。

类似的东西:

public static void main(String[] args) throws Exception {
    System.out.println(toSciNotation(1000123.456));         // would become 1.00E6 
    System.out.println(toSciNotation(-1123123.456));        // would become 1.1E-6 
    System.out.println(toSciNotation(1.2345678));           // would become 1.2345 
    System.out.println(toSciNotation(1000000000000L));      // would become 1.0E12
    System.out.println(toSciNotation(0.0000012345));        // would become 1.2E-6
    System.out.println(toSciNotation(0.0000000012345));     // would become 1.2E-9
    System.out.println(toSciNotation(12.12345E12));         // would become 1.2E13
}

private static String toSciNotation(double number) {
    return formatSciNotation(new DecimalFormat("0.00E0").format(number));
}

private static String toSciNotation(long number) {
    return formatSciNotation(new DecimalFormat("0.00E0").format(number));
}

private static String formatSciNotation(String strNumber) {
    if (strNumber.length() > 6) {
        Matcher matcher = Pattern.compile("(-?\\d+)(\\.\\d{2})(E-?\\d+)").matcher(strNumber);

        if (matcher.matches()) {
            int diff = strNumber.length() - 6;
            strNumber = String.format("%s%s%s", 
                    matcher.group(1),
                    // We add one back to include the decimal point
                    matcher.group(2).substring(0, diff + 1),
                    matcher.group(3)); 
        }
    }
    return strNumber;
}

结果:

1.00E6
-1.1E6
1.23E0
1.0E12
1.2E-6
1.2E-9
1.2E13