#include <stdio.h>
#include <stdlib.h>
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;
}
int main() {
double number;
unsigned prec;
printf("Enter a number: ");
// reads and stores input
scanf("%lf", &number);
printf("Enter precision: ");
// reads and stores input
scanf("%u", &prec);
char* result = format_width(number, prec);
// displays output
printf("You entered: %s", result);
free(result);
return 0;
}
To embed this program on your website, copy the following code and paste it into your website's HTML: