Home » C++ Tutorial » Setprecision C++ with Examples

# Setprecision C++ with Examples

A setprecision() is an in-built function defined in iomanip C++ header file. It is used to control the decimal number of output. If the setprecision() is called with n as an argument, it will convert the number with a precision of n argument.

Note: Using the Setprecision function on int will give output in an integer format. So C++ setprecision is not working on integer datatype.

## Syntax

setprecision(argument);

Where the argument is the count of decimal precision.

## How to use setprecision in C++?

To use setprecision, You must declare a number, and while printing, use the function and pass the count of the decimal number you want to print in the output as an argument.

If the number has 4 or 5 decimal points and you want to print 7 or 8 decimal points in the output use, C++ fixed setprecision. The use of fixed setprecision is shown below in the example.

## Examples of setprecision in C++

### 1. Using setprecision on the double data type.

#include <iostream> //header file for cout and fixed

#include <iomanip>  //header file for setprecision
using namespace std;

int main () {
double f =8.38274;
cout << setprecision(5) << f << '\n';
cout << setprecision(6) << f << '\n';
cout << fixed;
cout << "After using fixed precision" << '\n';
cout << setprecision(7) << f << '\n';
cout << setprecision(9) << f << '\n';
return 0;
}

Output

8.3827
8.38274
After using fixed precision
8.3827400
8.382740000

### 2. Using setprecision on the float data type.

#include <iostream> //header file for cout and fixed
#include <iomanip> //header file for setprecision
using namespace std;

int main (void)
{
float  a,b,c;
a = 22;
b = 7;
c = a/b;
cout << setprecision (1) << c << endl;
cout << setprecision (2) << c << endl;
cout << setprecision (3) << c << endl;
cout << setprecision (4) << c << endl;
cout << setprecision (5) << c << endl;
cout << setprecision (10) << c << endl;
return 0;
}

Output

3
3.1
3.14
3.143
3.1429
3.14285707473754882812

The fixed notation is declared in the C++ iostream header file . To use it, you must include iostream header file in the program. After using fixes precision, you can see the number of an argument passed to the function is a total count of decimal numbers. That means the setprecision function adds zero’s at the end of a number if the total count of numbers after the decimal point is less than passed argument.

Shares