I have some old C code I'm trying to replicate the behavior of in C++. It uses the printf
modifiers: "%06.02f".
I naively thought that iomanip
was just as capable, and did:
cout << setfill('0') << setw(6) << setprecision(2)
When I try to output the test number 123.456, printf
yields:
123.46
But cout
yields:
1.2+e02
Is there anything I can do in iomanip
to replicate this, or must I go back to using printf
?
[Live Example]
It can be used in C++ language too. Here is the syntax of printf() in C and C++ language, printf(“string and format specifier”, variable_name);
According to most sources I've found, across multiple languages that use printf specifiers, the %g specifier is supposed to be equivalent to either %f or %e - whichever would produce shorter output for the provided value.
The Printf module API details the type conversion flags, among them: %B: convert a boolean argument to the string true or false %b: convert a boolean argument (deprecated; do not use in new programs).
Try std::fixed
:
std::cout << std::fixed;
Sets the
floatfield
format flag for the str stream to fixed.When
floatfield
is set tofixed
, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision
) and with no exponent part.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With