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?

SheetJS
  • 22,470
  • 12
  • 65
  • 75
Foo Bah
  • 25,660
  • 5
  • 55
  • 79

3 Answers3

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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
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.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • @FooBah: See http://stackoverflow.com/questions/81656/where-do-i-find-the-current-c-or-c-standard-documents – Ben Voigt Sep 29 '11 at 14:20
1

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

Nick
  • 931
  • 6
  • 17
  • 3
    Wow, that's like trying to kill a mosquito with a thermo-nuclear warhead :-) – paxdiablo Sep 29 '11 at 03: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 '11 at 08:19