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

In C, we have an operator like:

printf("%6.3f ",floatNumber); 

which limits the number of digits when printing. A.
How can I achieve similar behavior in C++ ? I know setprecision , but that does not help me do the same.

+4
source share
2 answers

To get the same format specified in %6.3f using only standard iostream manipulators, you can do:

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

In particular, std::fixed indicates the same base format as f in the format string, so for example, "precision" means the same for the format string and for ostream. std::setprecision(3) then actually sets the precision, and std::setw(6) sets the field width. Without setting std::fixed you will get a format similar to the format specified in the format string "%6.3g" .

Note that besides setw these manipulators are sticky. That is, they remain valid after the release of one variable.

+7
source

It is best to use boost::format . See documentation , especially examples

Best of all (if you cannot use boost in your project), continue to use printf . This is part of the C ++ standard library, so it should "work" as long as you #include <stdio.h> just as always.

+4
source

All Articles