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
this an example using a matrix.
cout<<setprecision(4)<<fixed<<m[i][j]
with templates
#include <iostream>
// d = decimal places
template<int d>
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<int d>
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<int w, int d>
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<int d>
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<int w, int d>
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';
}
You were nearly there, need to use std::fixed as well, refer http://www.cplusplus.com/reference/iostream/manipulators/fixed/
#include <iostream>
#include <iomanip>
int main(int argc, char** argv)
{
float testme[] = { 0.12345, 1.2345, 12.345, 123.45, 1234.5, 12345 };
std::cout << std::setprecision(2) << std::fixed;
for(int i = 0; i < 6; ++i)
{
std::cout << testme[i] << std::endl;
}
return 0;
}
outputs:
0.12
1.23
12.35
123.45
1234.50
12345.00
To set fixed 2 digits after the decimal point use these first:
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
Then print your double values.
This is an example:
#include <iostream>
using std::cout;
using std::ios;
using std::endl;
int main(int argc, char *argv[]) {
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
double d = 10.90;
cout << d << endl;
return 0;
}
You have to set the 'float mode' to fixed.
float num = 15.839;
// this will output 15.84
std::cout << std::fixed << "num = " << std::setprecision(2) << num << std::endl;
I had an issue for integers while wanting consistent formatting.
A rewrite for completeness:
#include <iostream>
#include <iomanip>
int main()
{
// floating point formatting example
double d = 122.345;
std::cout << std::fixed << std::setprecision(2) << d << std::endl;
// Output: 122.34
// integer formatting example
int i = 122;
std::cout << std::fixed << std::setprecision(2) << double(i) << std::endl;
// Output: 122.00
}