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

标签 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

等等

我该如何实现? 问候, 克拉斯 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

关于java - 如何使用指数表示法将 double 转换为 n 字符的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30696132/

相关文章:

java - Spring Data Jpa 一对多关系。无法插入子记录 : foreign key is coming as NULL

java - 使泛型函数适用于多个非重叠类型

java - 如何在java中分割没有任何索引的字符串

emacs - 如何配置 GNU Emacs 默认写入 UNIX 或 DOS 格式的文件?

java - excel 中的日期格式与 apache poi

java - 将 java.util.Date 转换为字符串

java - 如何连接到远程HDFS

java - 在 CMD 中运行时出现 ClassNotFoundException

c++ - 如何在 C++ 中标记字符串?

string - 用于在目录和所有子目录中查找字符串的批处理脚本