Search code examples
c++cformat-string

What is the C++ equivalent of the c float precision command?


In C we have a statement like:

printf("%6.3f ",floatNumber);

which limits the number of digits when printing.
How can I achieve the similar behavior in C++ ? i know of setprecision but that doesn't help me do the same exact thing.


Solution

  • To get a similar format to that specified by %6.3f using just the standard iostream manipulators you can do:

    std::cout << std::fixed << std::setw(6) << std::setprecision(3) << f;
    

    Specifically std::fixed indicates the same basic format as f in the format string so that, for example, 'precision' means the same thing for both the format string and the ostream. std::setprecision(3) then actually sets the precision and std::setw(6) sets the field width. Without setting std::fixed you'd get a format similar to that specified by the format string "%6.3g".

    Note that except for setw these manipulators are sticky. That is, they remain in effect after the one variable is output.