编辑:如果指数为 17 位,此代码会导致小数部分丢失,因为我误解了 String.format 如何格式化这些数字。所以请不要使用此代码:P
感谢您的输入,伙计们。我找不到配置 DecimalFormat 或 NumberFormat 以完全克隆功能的方法,但似乎这种方法有效(后面有一个示例):
String.format("%.17g", x).replaceFirst("\\.?0+(e|$)", "$1");
主程序
#include <stdio.h>
int main (int argc, char const *argv[])
{
printf("%.*g\n", 17, -0.0);
printf("%.*g\n", 17, 0.0);
printf("%.*g\n", 17, 1.0);
printf("%.*g\n", 17, 1.2);
printf("%.*g\n", 17, 0.0000000123456789);
printf("%.*g\n", 17, 1234567890000000.0);
printf("%.*g\n", 17, 0.0000000123456789012345678);
printf("%.*g\n", 17, 1234567890123456780000000.0);
return 0;
}
主.java
class Main {
public static String formatDouble(double x) {
return String.format("%.17g", x).replaceFirst("\\.?0+(e|$)", "$1");
}
public static void main(String[] args) {
System.out.println(formatDouble(-0.0));
System.out.println(formatDouble(0.0));
System.out.println(formatDouble(1.0));
System.out.println(formatDouble(1.2));
System.out.println(formatDouble(0.0000000123456789));
System.out.println(formatDouble(1234567890000000.0));
System.out.println(formatDouble(0.0000000123456789012345678));
System.out.println(formatDouble(1234567890123456780000000.0));
}
}
及其输出:
$ gcc foo.c && ./a.out
-0
0
1
1.2
1.23456789e-08
1234567890000000
1.2345678901234567e-08
1.2345678901234568e+24
$ javac Main.java && java Main
-0
0
1
1.2
1.23456789e-08
1234567890000000
1.2345678901234567e-08
1.2345678901234568e+24