Showing posts with label setprecision(). Show all posts
Showing posts with label setprecision(). Show all posts

Tuesday, June 16, 2020

setprecision() in C++


Description:
It is used to set the decimal precision to be used to format floating-point values on output operations.
#include<iomanip> is required to use setprecision.

Declaration: 
setprecision(n);

Example:
Let's understand setprecision with a couple of examples.

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

int main(){
double n = 3.141516;
cout<<setprecision(5)<<n<<"\n";
cout<<setprecision(4)<<n<<"\n";
cout<<setprecision(3)<<n<<"\n";
cout<<setprecision(2)<<n<<"\n";
}

Output:
3.1415
3.142
3.14
3.1
----------------------
setprecision with fixed:
setprecision coupled with fixed will allow you to manipulate only the part after decimal point.

Example:
Let's understand setprecision with a couple of examples.

#include<iostream>
#include<iomanip>
using namespace std;
int main(){
double n = 3.141516;
cout<<fixed<<setprecision(5)<<n<<"\n";
cout<<fixed<<setprecision(4)<<n<<"\n";
cout<<fixed<<setprecision(3)<<n<<"\n";
cout<<fixed<<setprecision(2)<<n<<"\n";
}

Output:
3.14152
3.1415
3.142
3.14
As you can see the part after decimal point is manipulated.

horizontal ads