Ostream equivalent to% .2f or% .2lf

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

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

+8
source share
3 answers

Use setprecision in combination with fixed .

According to section 22.4.2.2.2 of the standard, precision specifications on iostreams have the same effect as printf . And fixed gives the same behavior as printf %f .

+4
source

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 prints 0.50 as desired.

+12
source
+1
source

All Articles