Skip to content
Advertisement

C compatible printf output for Java

I’d want to convert float/double to string, in Java and C, such that the outputs are both consistent and user friendly.

By “user friendly”, I mean the string should be human readable and sound: a maximum number of significant digits, and some automatic switching to scientific notation when appropiate (the double could span all the valid range).

By “consistent” I mean that the strings should be exactly the same in Java and C (I’d tolerate some exceptions if they are really rare).

Why not use simply some printf format string, as "%.5g"? That works… almost. But sadly the meaning of the precision field is quite different in Java and C. Also, the switching from-to scientific notation is not very consistent, nor even the format itself (2 or 3 digits for the exponent…). And different C compilers sometimes produce different results.

Examples of differences for "%.5g"

JavaScript

I can code a function in C or Java (or both), but I wonder if someone has already dealt with this. I’m not very concerned with performance, but yes with portability across C compilers.

Advertisement

Answer

Well, I ended coding my own functions. Tested with gcc and tcc over all the range of double, gives exactly the same output (except for very few very small values, less than 1E-319)

I post it in case someone finds it useful.

Java:

JavaScript

C:

JavaScript

Test code.

Java

JavaScript

C:

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