質問

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.

役に立ちましたか?

解決

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.

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top