Reputation: 87
C++ How to get fixed digit after decimal in output???? Like f=123.456789 I want to show 123.46 in output.
Upvotes: 0
Views: 3398
Reputation: 353
You'd require I/O manipulator for decimal precision.
#include <iomanip>
#include <iostream>
int main( )
{
double foo = 123.456789L;
std::cout << std::setprecision(2) << std::fixed << foo << std::endl;
return 0;
}
Upvotes: 0
Reputation: 7644
you could also use boost::format
#include <boost/format.hpp>
cout << boost::format("%.2f") % f << endl;
Upvotes: 0
Reputation: 1061
Another way is to use printf function, make sure that you include stdio.h file to use it,
printf("%0.2f",f);
Here %f is format specifier(float) and 0.2 between '%' and 'f' is used to set precision upto two decimal places.
Upvotes: 0
Reputation: 2375
You can use the setprecision() method in C++.
cout<<std::fixed<<std::setprecision(2)<<f;
Upvotes: 2