Search code examples
javacprintfformatter

What is the Java equivalent of C's printf %g format specifier?


I tried using Formatter.format, but that seems to leave the mantissa on numbers with 0 mantissa, whereas the C version does not. Is there an equivalent of C's %g format specifier in Java, and if not, is there a way to fake it? My intention is to preserve the mantissa exactly like C's for compatibility reasons.

foo.c

#include <stdio.h>

int main (int argc, char const *argv[])
{
    printf("%g\n", 1.0);
    return 0;
}

Main.java

class Main {
        public static void main(String[] args) {
                System.out.printf("%g\n", 1.0);
        }
}

Console:

$ javac Main.java && java Main
1.00000
$ gcc foo.c && ./a.out
1

Similarly, with 1.2 as input, the mantissa is longer in Java's version

$ javac Main.java && java Main
1.20000
$ gcc foo.c && ./a.out
1.2

Solution

  • Have you tried the java.text.DecimalFormat class?

    System.out.println(new DecimalFormat().format(1.0));
    

    outputs:

    1
    

    whereas:

    System.out.println(new DecimalFormat().format(1.2));
    

    outputs:

    1.2