Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a number to variable number of decimal places

Tags:

c

I wanted to print a number to variable number of decimal places in C. I have written the code

#include<stdio.h>
main()
    {   int a;
        printf("Upto which number of decimal places you want to print value of '2.554648' ?");
        scanf("%d", &a);
        printf("Value of '2.554648 upto %d number of decimal places = %.af", a, 2.554648);
        return 0;
    }
like image 494
Mradul Verma Avatar asked Jan 09 '23 11:01

Mradul Verma


1 Answers

Use * in printf() to mark how many decimal places you want:

#include <stdio.h>

int main(void)
{
    int a;

    printf("Upto which number of decimal places you want to print value of '2.554648' ?");
    scanf("%d", &a);
    printf("Value of '2.554648 upto %d number of decimal places = %.*f", a, a, 2.554648);

    return 0;
}
like image 131
Grzegorz Szpetkowski Avatar answered Jan 18 '23 01:01

Grzegorz Szpetkowski