user6720691
user6720691

Reputation: 55

How to let user decide how many decimal places they want printed in their float?

How would I make a program allow the user to choose how many decimal spaces they would like to see printed in their float value?

For example, the following code

#include <stdio.h>
int main(){
    float x;
    x = 0.67183377;
    printf("%.2f\n", x);
}

Would give us an output of 0.67.But what if the user wanted to see the full number, or up to the fourth decimal place, for example. How would they do this?

Upvotes: 2

Views: 679

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753455

See printf() for the details. Use:

printf("%.*f\n", n, x);

where n is an int that contains the number of decimal places to be printed. Note that a float can only really hold about 6-7 decimal digits; the 8th one in the example will be largely irrelevant.

#include <stdio.h>

int main(void)
{
    float x = 0.67183377;
    for (int n = 0; n < 10; n++)
        printf("%.*f\n", n, x);
    return(0);
}

Example output:

1
0.7
0.67
0.672
0.6718
0.67183
0.671834
0.6718338
0.67183375
0.671833754

The value is converted to a double before it is passed to printf() because that happens with all variadic functions. When x is changed to a double, the output is:

1
0.7
0.67
0.672
0.6718
0.67183
0.671834
0.6718338
0.67183377
0.671833770

Upvotes: 7

Related Questions