31

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)
Wolf
  • 9,679
  • 7
  • 62
  • 108
Wine Too
  • 4,515
  • 22
  • 83
  • 137
  • REMOVED: EDIT - Solution: (for rounding and clearing a float number to desired precision). ```c int precision = 2; char kolf[16] = {0}; sprintf(kolf, "%8.*f", precision, mystruct.myfloat); float kol = atof(kolf); ``` – Wolf Jan 12 '21 at 08:49

3 Answers3

57

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
Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
32

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

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.

Wolf
  • 9,679
  • 7
  • 62
  • 108