views:

854

answers:

4

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
A: 

well, you can specify how many digits you want: "%.2g" will display 1.2 as 1.20

the problem is that will truncate the mantissa if it has more than 2 digits. I didn't say it in the question, but my intention is to preserve the mantissa exactly like C's for compatibility reasons. As far as I can tell, C's %g will put as many digits in the mantissa as necessary but no more.
John Douthat
+1  A: 

You could use a NumberFormat. By setting the minimum fraction digits to 0, but leaving the maximum bigger, it should do what you want.

It's not as easy as printf, but it should work.

MBCook
+2  A: 

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
highlycaffeinated
+3  A: 
John Douthat