如何使用指数表示法将双精度数转换为 n 字符的字符串?

How do I convert a double into an n-character string using exponential notation?

我在 SO 上多次发现这个反之亦然,但从来没有像我想要的那样。

我想将双精度数转换成一个字符串,它正好 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

等等

我该如何实现? 问候, 克拉斯 M.

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

如果您将指数分量限制为 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