Reputation: 721
What is the best way to remove leading and trailing zeros from C++ string formatters that use %f. There's a similar question Avoid trailing zeroes in printf() but that just says to use the %g formatter.
The %g formatter will output 600000000009 as 6e+11
I just want to remove the leading and trailing zeros from %f eg:
Any thoughts/suggestions welcome. Thanks.
Upvotes: 1
Views: 1010
Reputation: 114491
A dynamic format that works in most cases is just
%.15g
that means up to 15 digits of precision.
An even better approach is to start from 15 digits and check back if atof(result)
is the same as the input, incrementing the number of digits until it does match.
Using directly the maximum number of digits can be a bad idea because formatting for example 0.1
with 18 digits will bring out a representation that will look strange for the user.
Upvotes: 2