Show specific number of digits after decimal point in C++

In this tutorial, let’s learn about how to display a specific number of digits after the decimal point in C++.

iomanip

It is the header file in c++ which contains functions that formats the outputs displayed in C++.

setprecision() is one of the functions under iomanip header file

setprecision()

It is a function that sets the precision for decimal and float values.

This formats the floating values which are displayed.

syntax

setprecision(int n)

here, the parameter should be an integer that specifies the number of digits to be displayed after the decimal point.

example 1

#include <iostream>
#include <iomanip>

int main()
{
    double d = 122.3415;
    std::cout << std::fixed << std::setprecision(3) << d;
}
Output
122.341

Since we have set precision as 3, the 3 digits after the decimal point are displayed.

example 2

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

int main() {
    
    float d = 67.908768;
    double e = 65715.98747986868469;
    cout<<fixed<<setprecision(3)<<d<<"\n";
    cout<<fixed<<setprecision(9)<<e;
    return 0;
}

Output

67.909
65715.987479869

In this example, we see how setprecision() function performs on double and float values.

Leave a Reply

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