• Register
search
Log In

We have some fractions like ⅓ which is equal to 0.3333333333… and so on. It has infinite length and it will require infinite memory to store this value in memory and we cannot do that since generally we have 4 or max 8 bytes of memory for a variable.  Therefore, we can store floating points to a certain size i.e., we can store a few of the digits after the decimal and the remaining will be lost.

To overcome this problem, we use precision, precision of floating point defines how many digits it can display after decimal. 

Formatting output is important in development of output screens, which can be easily read and understood. C++ offers several i/o manipulators. Two of them are

  • setw()

  • setprecision()

 

setprecision() manipulator

It sets the total number of digits to be displayed when floating point numbers are printed. For example

cout << setprecision(5) << 123.456;

Output

123.46 //Notice the rounding

It can also be used to set the number of decimal places to be displayed. In order to accomplish this task, you will have to set an ios flag.

cout.setf(ios::fixed);
cout << setprecision(5) << 12.345678;

Output

12.34567 //Notice rounding

Program

// C++ program to demonstrate working of setprecision() 
// in C/C++ 
#include<bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    double pi = 3.14159, npi = -3.14159; 
    cout << fixed << setprecision(0) << pi <<" "<<npi<<endl; 
    cout << fixed << setprecision(1) << pi <<" "<<npi<<endl; 
    cout << fixed << setprecision(2) << pi <<" "<<npi<<endl; 
    cout << fixed << setprecision(3) << pi <<" "<<npi<<endl; 
    cout << fixed << setprecision(4) << pi <<" "<<npi<<endl; 
    cout << fixed << setprecision(5) << pi <<" "<<npi<<endl; 
    cout << fixed << setprecision(6) << pi <<" "<<npi<<endl; 
} 

Output

3 -3
3.1 -3.1
3.14 -3.14
3.142 -3.142
3.1416 -3.1416
3.14159 -3.14159
3.141590 -3.141590
posted Jun 20 in c++ 100 points