edit : This code causes the fractional part to be skipped if the exponent is 17 digits, due to my misunderstanding of how String.format formatted these numbers. So please do not use this code: P
Thanks for the entry guys. I couldn't find a way to configure DecimalFormat or NumberFormat to clone functions exactly, but this method seems to work (followed by an example):
String.format("%.17g", x).replaceFirst("\\.?0+(e|$)", "$1");
main.c
#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; }
Main.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)); } }
and their outputs:
$ gcc foo.c && ./a.out
-0
0
one
1.2
1.23456789e-08
1234567890000000
1.2345678901234567e-08
1.2345678901234568e + 24
$ javac Main.java && java Main
-0
0
one
1.2
1.23456789e-08
1234567890000000
1.2345678901234567e-08
1.2345678901234568e + 24
John douthat
source share