'Printf variable number of decimals in float
I found interesting format for printing nonterminated fixed length strings like this:
char newstr[40] = {0};
sprintf(newstr,"%.*s", sizeof(mystr), mystr);
So I think maybe is there a way under printf command for printing a float number...
"%8.2f"
to have ability to choose number of decimals with integer number.
Something like this:
sprintf(mystr, "%d %f", numberofdecimals, floatnumbervalue)
Solution 1:[1]
You can also use ".*" with floating points, see also http://www.cplusplus.com/reference/cstdio/printf/ (refers to C++, but the format specifiers are similar)
.number: For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
...
.*: The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
For example:
float floatnumbervalue = 42.3456;
int numberofdecimals = 2;
printf("%.*f", numberofdecimals, floatnumbervalue);
Output:
42.35
Solution 2:[2]
You can use the asterisk for that too, both for the field width and the precision:
printf("%*.*f\n", myFieldWidth, myPrecision, myFloatValue);
See e.g. this reference.
Solution 3:[3]
If, for some reason, your actual C library doesn't support variable precision and width for float formatting, it's not too hard to build the format string your own:
char fmt[6 + 3*(sizeof width + sizeof precision)]; /* sufficient space */
sprintf(fmt, "%%%d.%df\n", width, precision);
printf(fmt, value);
Of course this comes at a cost, but - depending on your situation - this can be maybe centralized.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Some programmer dude |
| Solution 3 |
