Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print float/double without trailing zeros? [duplicate]

Tags:

c

There are a few questions related to this, but I haven't seen one that correctly answers this question. I want to print a floating-point number, but I want the number of decimal places to be adaptive. As an example:

0      -> 0
1234   -> 1234
0.1234 -> 0.1234
0.3    -> 0.3

Annoyingly, the %f specifier will only print to a fixed precision, so it will add trailing zeros to all numbers that don't reach that precision. Some have suggested the %g specifier, which works for a set of numbers, but it will switch to scientific notation for some numbers, like this:

printf("%g", 1000000.0); // prints 1e+06

How can I print floating-point numbers without the unnecessary zeros, while still maintaining printf's standard accuracy for numbers that actually have fractional components?

like image 822
Alexis King Avatar asked Dec 02 '22 20:12

Alexis King


1 Answers

Use snprintf to print to a temporary buffer then remove the trailing '0' characters manually. There is no other way that's both correct and reasonably easy to implement.

like image 177
R.. GitHub STOP HELPING ICE Avatar answered Dec 15 '22 11:12

R.. GitHub STOP HELPING ICE