pico-sdk
pico-sdk copied to clipboard
Make printf trim trailing zeroes with %[Gg] format
This PR modifies the behavior of pico_printf
to automatically trim trailing zeroes when using the %G
or %g
format specifiers. This is the behavior that is specified by GCC:
The ‘
%g
’ and ‘%G
’ conversions print the argument in the style of ‘%e
’ or ‘%E
’ (respectively) if the exponent would be less than -4 or greater than or equal to the precision; otherwise they use the ‘%f
’ style. A precision of0
, is taken as 1. Trailing zeros are removed from the fractional portion of the result and a decimal-point character appears only if it is followed by a digit.
Previously, printf("%.14g", 2000)
would output 2000.0000000000
, but with this change it outputs just 2000
. This is useful for programs that want the minimum-length conversion of a number with the most precision necessary. (My example is Lua, which uses sprintf(s, "%.14g", num)
to convert numbers to strings; previously this would result in unnecessarily large conversions for small integers.)
This change does not affect the default printf
- newlib exhibits the same behavior as pico_printf
currently does, so that would have to be adjusted as well (and I can say after reading the code that I'm not the one to do that). Users will have to link pico_printf
manually to benefit AFAICT.
Please let me know if this breaks anything - I didn't have a chance to test this fully (I'm embroiled in debugging some other stuff), but looking at the code I don't think there should be much to break.
Note that people using the SDK CMake build get pico_printf by default.