How to use setprecision in C++
Solution 1:
#include <iomanip>
#include <iostream>
int main()
{
double num1 = 3.12345678;
std::cout << std::fixed << std::showpoint;
std::cout << std::setprecision(2);
std::cout << num1 << std::endl;
return 0;
}
Solution 2:
#include <iostream>
#include <iomanip>
using namespace std;
You can enter the line using namespace std;
for your convenience. Otherwise, you'll have to explicitly add std::
every time you wish to use cout
, fixed
, showpoint
, setprecision(2)
and endl
int main()
{
double num1 = 3.12345678;
cout << fixed << showpoint;
cout << setprecision(2);
cout << num1 << endl;
return 0;
}
Solution 3:
The answer above is absolutely correct. Here is a Turbo C++ version of it.
#include <iomanip.h>
#include <iostream.h>
void main()
{
double num1 = 3.12345678;
cout << setiosflags(fixed) << setiosflags(showpoint);
cout << setprecision(2);
cout << num1 << endl;
}
For fixed
and showpoint
, I think the setiosflags
function should be used.
Solution 4:
Replace These Headers
#include <iomanip.h>
#include <iomanip>
With These.
#include <iostream>
#include <iomanip>
using namespace std;
Thats it...!!!
Solution 5:
std::cout.precision(2);
std::cout<<std::fixed;
when you are using operator overloading try this.