Reputation:
I want to control how many digits will be printed after the decimal point when printing a float.
The function will take n
as an input.
For example, if I have double F = 123.456789
, and:
123.46
123.457
123.4567890000
Upvotes: 0
Views: 4413
Reputation: 3377
Use format specifiers. Examples:
%.4f (print as a floating point with a precision of four characters after the decimal point)
%3.2f (print as a floating point at least 3 wide and a precision of 2)
Please read: http://www.codingunit.com/printf-format-specifiers-format-conversions-and-formatted-output
Upvotes: 0
Reputation: 59701
This should work for you:
#include <stdio.h>
int main() {
int n = 2;
double number = 123.456789;
printf("%.*lf", n, number);
return 0;
}
Output:
123.46
Upvotes: 2
Reputation: 13804
You can do:
printf("%.2lf\n", F);
printf("%.3lf\n", F);
printf("%.10lf\n", F);
As you want to control it, you can use *
modifier as a placeholder.
int n;
double F = 123.456789;
scanf("%d", &n);
printf("%.*lf\n",n, F);
Upvotes: 3