Set precision dynamically with sprintf

Using sprintf and the general syntax "%AB" , I can do this:

 double a = 0.0000005l; char myNumber[50]; sprintf(myNumber,"%.2lf",a); 

Can I set A and B dynamically to a format string?

+6
source share
2 answers

Yes you can do it. You must use an asterisk * as the field width and .* As the precision. Then you need to provide arguments that carry values. Sort of

  sprintf(myNumber,"%*.*lf",A,B,a); 

Note: A and B must be of type int . From the C11 standard, chapter §7.21.6.1, fprintf() function

... the width of the field, or the accuracy, or both, can be indicated by an asterisk. In this case, the int argument provides the field width or precision. Arguments indicating the width of the field, or precision, or both, must be displayed (in that order) before converting the argument (if any). The negative field width argument is taken as the - flag, followed by the positive field width. The negative precision argument is accepted as if the precision were omitted.

+9
source

Yes - you use "*", for example.

 sprintf(mynumber, "%.*lf", 2, a); 

See http://linux.die.net/man/3/sprintf

+4
source

Source: https://habr.com/ru/post/989594/


All Articles