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:

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:

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.