简体   繁体   中英

Print a variable number of digits of a double using printf

Anyone knows if it is possible to use printf to print a VARIABLE number of digits?

The following line of code prints exactly 2:

printf("%.2lf", x);

but let's say I have a variable:

int precision = 2;

Is there a way to use it in printf to specify the number of digits?

Otherwise I will have to write a 'switch' or 'if' structure.

Thanks

It is possible:

#include <stdio.h>

int main() {
    int precision = 3;
    float b = 6.412355;
    printf("%.*lf\n",precision,b);
    return 0;
}

Yes, you can do that easily -

int precision = 2;
printf("%.*lf", precision, x);

Yes: printf("%*d", width, num) : see here: http://linux.die.net/man/3/printf

If you are using C++ you could use std::cout in combiation with ios_base::precision() : http://www.cplusplus.com/reference/ios/ios_base/precision/

If you use C++, you can use setprecision :

#include <iostream>
#include <iomanip>      // std::setprecision

int main () {
    int precision = 2;
    double f =3.14159;

    std::cout << std::setprecision(precision) << f << '\n';
    ++precision;
    std::cout << std::setprecision(precision) << f << '\n';

    return 0;
}

Output :

3.1
3.14

You can read more about it here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM