Skip to content
Advertisement

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

JavaScript

Main.java

JavaScript

Console:

JavaScript

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

JavaScript

Advertisement

Answer

Have you tried the java.text.DecimalFormat class?

JavaScript

outputs:

JavaScript

whereas:

JavaScript

outputs:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement