Home > Blockchain >  How can i print up to x decimal numbers in printf?
How can i print up to x decimal numbers in printf?

Time:11-28

I need to know how can print up to 6 or 2 decimal numbers in print?

int main(){
    double a = 2.1324456789;
    printf("%lf",a);
    return 0;
    }

CodePudding user response:

You should change you syntax in printf. if you want to print up to 6 decimal digits you can do this:

int main(){
double a = 2.1234456789;
printf("%6lf",a);
return 0;
}

and if you want to print up to 4 decimal digits you can change 6 to 4.

CodePudding user response:

#include <stdio.h>

int main(void) {
    double a = 2.1324456789;
    printf("%.6lf\n", a);     // 2.132446
    printf("%.*lf\n", 6, a);  // 2.132446
    printf("%.2lf\n", a);     // 2.13
    printf("%.*lf\n", 2, a);  // 2.13
    return 0;
}
  • Related