c++ printf float - how to specify precision programmatically?

Viewed 159

printf("float: %.3f", myvar); prints myvar with 3 digits after the dot. But how can I do that if the number of digits I want to print is dynamic and specified in an int variable?

2 Answers

You can use %.*f and add the int value before the data to print.

#include <cstdio>

int main(void) {
    double myvar = 3.141592653589;
    for (int i = 0; i < 10; i++) {
        printf("float: %.*f", i, myvar);
        putchar('\n');
    }
    return 0;
}

To be more into modern c++, and as alternative to MikeCAT response

#include <iomanip>
#include <iostream>


int main()
{
    constexpr int precision = 2;
    std::cout << std::fixed << std::setprecision( precision ) << 10.1234 << std::endl; // outputs: 10.12
    return 0;
}
Related