I have a list of float
values and I want to print them with cout
with 2 decimal places.
For example:
10.900 should be prin
with templates
#include
// d = decimal places
template
std::ostream& fixed(std::ostream& os){
os.setf(std::ios_base::fixed, std::ios_base::floatfield);
os.precision(d);
return os;
}
int main(){
double d = 122.345;
std::cout << fixed<2> << d;
}
similar for scientific as well, with a width option also (useful for columns)
// d = decimal places
template
std::ostream& f(std::ostream &os){
os.setf(std::ios_base::fixed, std::ios_base::floatfield);
os.precision(d);
return os;
}
// w = width, d = decimal places
template
std::ostream& f(std::ostream &os){
os.setf(std::ios_base::fixed, std::ios_base::floatfield);
os.precision(d);
os.width(w);
return os;
}
// d = decimal places
template
std::ostream& e(std::ostream &os){
os.setf(std::ios_base::scientific, std::ios_base::floatfield);
os.precision(d);
return os;
}
// w = width, d = decimal places
template
std::ostream& e(std::ostream &os){
os.setf(std::ios_base::scientific, std::ios_base::floatfield);
os.precision(d);
os.width(w);
return os;
}
int main(){
double d = 122.345;
std::cout << f<10,2> << d << '\n'
<< e<10,2> << d << '\n';
}