Printf variable number of decimals in float

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

Leave a Comment