简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM