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;
}
1 Comment
matthias_buehlmann
great, and for potentially other values to substitute in the string it remains one parameter? for example:
printf("%s%.*f%s", "float: ", i, myvar, " $"); ?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
Marek R
setprecision is to old to be called "modern c++".Krzysztof Mochocki
whoa, didn't know about it, what's new. It seems i am out of date @MarekR
Marek R
fmt will become part of C++20 standard this will be more handy (short as C version and type safe).Krzysztof Mochocki
Looks, NOIZZ
chararray 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)