user2361274
user2361274

Reputation:

How do I control the number of decimal places printed in a float?

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:

Upvotes: 0

Views: 4413

Answers (3)

Jobs
Jobs

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

Rizier123
Rizier123

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

Shahriar
Shahriar

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

Related Questions