ostream equivalent of %.2f or %.2lf
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.
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
.