![]() |
VOOZH | about |
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
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.
cout << setprecision(int n) << num;
Here, n is the number of decimal places we want to output.
The below example demonstrates how we can use the setprecision() method to set the precision of floating-point numbers in C++.
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 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.