Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
iomanip
setprecision

What is the setprecision function in C++?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The setprecision() function is a built-in function that comes with the iomanip library. As the name suggests, it helps us to set the precision (significant figures/decimal​ places) of an output.

Significant figures

The function takes in one argument: the number of significant figures required in the ​output.

svg viewer
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float pi = 3.141592;
cout << setprecision(4) << pi;
}

Decimal places

To manipulate the decimal places being displayed in the output, add a fixed keyword before the setprecision() function (as shown below). The function will still take in only ​one argument, but it will be the number of decimal places required in the output.

svg viewer
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float pi = 3.141592;
cout << fixed << setprecision(4) << pi;
}

RELATED TAGS

c++
iomanip
setprecision
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring