Open In App

How to use setprecision in C++?

Last Updated : 17 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, we have a std::setprecision function which is a part of the <iomanip> library. It is used to set the number of decimal places to be displayed for a floating-point number. In this article, we will learn how to use the setprecision function in C++.

Example:

Input: 
double num = 3.142857142857;

Output: 
3.14 // precision set to 2 decimal places

Using setprecision() Function in C++

In C++, the default precision of floating-point numbers can be changed by specifying the number of decimal places to be output inside the setprecision() method. It is applied to the whole number, including the integer and fractional parts, and uses scientific notation when the number is large and exceeds the specified precision.

Syntax of setprecision in C++

cout << setprecision(int n) << num;

Here, n is the number of decimal places we want to output.

C++ Program to Show the Use of setprecision()

The below example demonstrates how we can use the setprecision() method to set the precision of floating-point numbers in C++.

C++
// C++ Program to demonstrate the use of setprecision
#include <iomanip>
#include <iostream>
using namespace std;

int main()
{
    // Initializing a decimal number
    double num = 3.142857142857;

    // Displaying the number before setting precision
    cout << "Before setting the precision: " << num << endl;

    // Setting the precision to 3 and displaying the number
    cout << "After setting the precision to "
            "3: "
         << setprecision(3);
    cout << num << endl;

    // Setting the precision to 5 and displaying the number
    cout << "After setting the precision to "
            "5: "
         << setprecision(5);
    cout << num << endl;

    return 0;
}

Output
Before setting the precision: 3.14286
After setting the precision to 3: 3.14
After setting the precision to 5: 3.1429

Time Complexity: O(1)
Auxiliary Space: O(1)

Note: The setprecision() function will only alter the precision of the output and not the actual value of the floating-point number, default value is fixed and is an inherent part of the datatype.


Next Article
Practice Tags :

Similar Reads