Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

Your best option would be to use boost::format. See the documentation, especially the examples

Next best (if you can't use boost in your project) is to keep using printf. It's part of the C++ Standard Library so it should "just work" as long as you #include <stdio.h> just like always.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top