I keep stumbling on the format specifiers for the printf() family of functions. What I want is to be able to print a double (or float) with a maximum given number of digits after the decimal point. If I use:
printf("%1.3f", 359.01335);
printf("%1.3f", 359.00999);
I get
359.013
359.010
Instead of the desired
359.013
359.01
Can anybody help me?
Best Answer
This can't be done with the normal
printf
format specifiers. The closest you could get would be:but the ".6" is the total numeric width so
breaks it.
What you can do is to
sprintf("%.20g")
the number to a string buffer then manipulate the string to only have N characters past the decimal point.Assuming your number is in the variable num, the following function will remove all but the first
N
decimals, then strip off the trailing zeros (and decimal point if they were all zeros).If you're not happy with the truncation aspect (which would turn
0.12399
into0.123
rather than rounding it to0.124
), you can actually use the rounding facilities already provided byprintf
. You just need to analyse the number before-hand to dynamically create the widths, then use those to turn the number into a string:The whole point of
nDecimals()
in this case is to correctly work out the field widths, then format the number using a format string based on that. The test harnessmain()
shows this in action:Once you have the correctly rounded value, you can once again pass that to
morphNumericString()
to remove trailing zeros by simply changing:into:
(or calling
morphNumericString
at the end ofnDecimals
but, in that case, I'd probably just combine the two into one function), and you end up with: