[c++] How to use setprecision in C++

I am new in C++ , i just want to output my point number up to 2 digits. just like if number is 3.444, then the output should be 3.44 or if number is 99999.4234 then output should be 99999.42, How can i do that. the value is dynamic. Here is my code.

#include <iomanip.h>
#include <iomanip>
int main()
{
    double num1 = 3.12345678;
    cout << fixed << showpoint;
    cout << setprecision(2);
    cout << num1 << endl;
}

but its giving me an error, undefined fixed symbol.

This question is related to c++

The answer is


#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;
}

#include <bits/stdc++.h>                        // to include all libraries 
using namespace std; 
int main() 
{ 
double a,b;
cin>>a>>b;
double x=a/b;                                 //say we want to divide a/b                                 
cout<<fixed<<setprecision(10)<<x;             //for precision upto 10 digit 
return 0; 
} 

input: 1987 31

output: 662.3333333333 10 digits after decimal point


std::cout.precision(2);
std::cout<<std::fixed;

when you are using operator overloading try this.


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.


#include <iostream>
#include <iomanip>
 
int main(void) 
{
    float value;
    cin >> value;
    cout << setprecision(4) << value;
    return 0;
}

Below code runs correctly.

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    double num1 = 3.12345678;
    cout << fixed << showpoint;
    cout << setprecision(2);
    cout << num1 << endl;
}

Replace These Headers

#include <iomanip.h>
#include <iomanip>

With These.

#include <iostream>
#include <iomanip>
using namespace std;

Thats it...!!!


#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;
}