Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 885
Hossein Avatar asked Dec 20 '22 10:12

Hossein


2 Answers

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.

like image 157
bames53 Avatar answered Dec 22 '22 23:12

bames53


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.

like image 36
Ben Voigt Avatar answered Dec 22 '22 22:12

Ben Voigt