2

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?

1
  • The format string doesn't have to be a string literal. You can write your own format string in a char array on the fly. (I'd have written an answer with code to demonstrate this, but there's already an accepted answer, so I'm not going to waste my time) Commented Sep 1, 2020 at 15:12

2 Answers 2

11

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

great, and for potentially other values to substitute in the string it remains one parameter? for example: printf("%s%.*f%s", "float: ", i, myvar, " $"); ?
3

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;
}

4 Comments

setprecision is to old to be called "modern c++".
whoa, didn't know about it, what's new. It seems i am out of date @MarekR
fmt will become part of C++20 standard this will be more handy (short as C version and type safe).
Looks, NOIZZ

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.