Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ostream equivalent of %.2f or %.2lf

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?

like image 933
Foo Bah Avatar asked Sep 29 '11 03:09

Foo Bah


1 Answers

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.

like image 78
paxdiablo Avatar answered Nov 08 '22 01:11

paxdiablo