Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing printf("%g", value) with a stream manipulation

Tags:

c++

iostream

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:

  • 544666.678 is written as 544667 if %.6g is used,
  • The same number is written as 5.4467E+5 when %.5g is used.
like image 212
Matthieu Brucher Avatar asked May 31 '19 08:05

Matthieu Brucher


1 Answers

%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

like image 140
L. F. Avatar answered Oct 25 '22 05:10

L. F.