I wanted to replace an implementation of:
float value = 3.14;
printf("%g", value);
(See How %g works in printf for the explanation of %g
if required).
But I haven't found an equivalent in the stream manipulators, only for either fixed or scientific, but not the shortest of both (https://en.cppreference.com/w/cpp/io/manip/fixed). Does this exist or is there a "simple" way to implement this?
Some examples from the linked SO question:
%.6g
is used,%.5g
is used.%g
is the default behavior. For example:
#include <iomanip>
#include <iostream>
int main()
{
std::cout << std::setprecision(6) << 544666.678 << "\n"
<< std::setprecision(5) << 544666.678 << "\n";
}
Output:
544667
5.4467e+05
The default behavior can be retained with the manipulator std::defaultfloat
after std::fixed
or std::scientific
is set.
Live demo
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