9
double d = 1/2.;
printf("%.2lf\n", d);

This prints out 0.50. This is what I want to replicate using ostream manipulators. However, none of the obvious iomanip manipulators let me set the minimum required decimal places (if I understood correctly, setprecision sets the maximum width). Is there a pure iostream or boost way to do this?

3 Answers 3

13

You can use std::fixed and std::setprecision from the iomanip header:

#include <iostream>
#include <iomanip>
int main(void) {
    double d = 1.0 / 2;
    std::cout << std::fixed << std::setprecision(2) << d << std::endl;
    return 0;
}

This outputs 0.50 as desired.

4

Use setprecision in combination with fixed.

According to section 22.4.2.2.2 of the standard, precision specifications on iostreams have exactly the same effect as they do for printf. And fixed gives the exact same behavior as printf's %f.

1
1

The boost way: http://www.boost.org/doc/libs/1_47_0/libs/format/doc/format.html.

2
  • 3
    Wow, that's like trying to kill a mosquito with a thermo-nuclear warhead :-)
    – paxdiablo
    Sep 29, 2011 at 3:50
  • @paxdiable: No it solves a real problem. printf is not type-safe (and works with a handful of types), with streams formatting is painful (and in certain cases you absolutely need to be able to use a format string).
    – visitor
    Sep 29, 2011 at 8:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.