Rafael
Rafael

Reputation: 452

Is there a way of control the wide and precision of a float in the printf() function in C?

How can I control the wide (width) and the precision, for example using two integers int a and int b to which I can assign a value before in the code?

printf("%a.bf\n", floatVariable);

Upvotes: 3

Views: 70

Answers (1)

Pascal Cuoq
Pascal Cuoq

Reputation: 80255

The symbol * in place of the numerical value can be used for this:

printf("%*.*f\n", a, b, floatVariable);

Each * in the format string where a numerical value is expected causes an int argument to be consumed from the argument list and used as the numerical value.

Note that just like floatVariable must be of type double or float if you pass it to be printed with %f, the variables a and b must be of type int for this notation to work. If they aren't, you must use:

printf("%*.*f\n", (int)a, (int)b, floatVariable);

Upvotes: 4

Related Questions