setprecision in C++ with examples

In this tutorial, let’s have a look at setprecision in C++ with some examples.

setprecision()

It is part of the <iomanip> header which consists of functions that are
used to manipulate the output of the C++ program.

Setprecision() function is employed to set the decimal precision for floating-point values which ends up in their
formatting when being displayed. It is inserted or extracted on both- input
or output streams.

Syntax:-

setprecision(int n);

Here n is the value that should be passed to set the number of values after the decimal point.

The above function does not return anything, because it’s a string manipulator.

Example 1

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

int main()
{
   int num = 45674;
  cout << setprecision(3) << num ;
  
  return 0;
}

Output

45674

In the above example, the number declared is int, setprecision() function is only effective for float and double values.

Example 2

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

int main()
{
  float num = 45674.8998;
  cout <<fixed<< setprecision(3) << num ;
  
  return 0;
}

Output

45674.898

In the above example, we use float values and precision is set to 3.

Example 3

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

int main()
{
  double num = 987012.87553620264;
  cout <<fixed<< setprecision(9) << num ;
  
  return 0;
}

Output

987012.875536203

In the above example, we have taken a double value for which the precision is set to be 9.

Therefore, 9 digits are displayed after the decimal point.

 

Leave a Reply

Your email address will not be published. Required fields are marked *