I believe what you are looking for is a way to dynamically change the precision of the output without having to hardcode it.
If you have access to a c99 compiler, you can generate format strings by using snprintf
like:
char* format_width(double x, unsigned prec) {
int fmt_size = snprintf (NULL, 0, "%%.%ulf", prec);
char* fmt_string = malloc(fmt_size + 1);
snprintf(fmt_string, fmt_size + 1, "%%.%ulf", prec);
int out_size = snprintf (NULL, 0, fmt_string, x);
char* out_string = malloc(out_size + 1);
snprintf(out_string, out_size + 1, fmt_string, x);
free(fmt_string);
return out_string;
}
Usage could be something like
int main() {
double number;
unsigned prec;
printf("Enter a number: ");
// reads and stores input
scanf("%lf", &number);
printf("Enter precision: ");
// reads and stores precision
scanf("%u", &prec);
char* result = format_width(number, prec);
// displays output
printf("You entered: %s", result);
free(result);
return 0;
}
Demo
Optimizing allocations
In order to avoid too many allocations, one could make use of a buffer of reasonable size to generate the format specifier. For example, it is very unlikely that the fmt_string
will ever exceed 15 characters, so we can optimize that part.
It may also be possible that the user already knows the maximum size of input they may ever receive, so we can allow them to pass in the out_string
buffer (which is assumed to be large enough to contain the result)
char* format_width(double x, unsigned prec, char* out_string) {
static char fmt_string[15];
snprintf(fmt_string, 15, "%%.%ulf", prec);
int out_size = snprintf (NULL, 0, fmt_string, x);
snprintf(out_string, out_size + 1, fmt_string, x);
return out_string;
}