The setprecision C++ function is used to format floating-point values. This is an inbuilt function and can be used by importing the iomanip library in a program. By using the setprecision function, we can get the desired precise value of a floating-point or a double value by providing the exact number of decimal places. If an argument n is passed to the setprecision() function, then it will give n significant digits of the number without losing any information. 

n C++, the setprecision function plays a crucial role in controlling the precision of floating-point numbers during output operations, allowing developers to specify the exact number of digits to display after the decimal point.

While mastering such intricacies of C++ is essential for software development, expanding your skill set to include multiple programming languages and frameworks can significantly enhance your career opportunities. Enrolling in a java full stack developer course will not only deepen your understanding of Java

Syntax of C++ Setprecision

The syntax of the setprecision() function in C++ is as follows:

setprecision (int n)

Parameter description:

  1. Argument: This parameter is of integer type and is used to specify the number of significant digits required for a floating-point or double value. When you pass a value 'n' to this parameter, the floating-point number will be displayed with exactly 'n' significant digits.

  2. Return Value: This function does not return a value. It only manipulates streams.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Significant Figures and Decimal Places

The C++ setprecision can be used to manipulate a complete floating-point value or just its decimal places. These two cases are discussed below:

Significant Figures

To set the precision in a floating-point, simply provide the number of significant figures (say n) required to the setprecision() function as an argument. The function will format the original value to the same number of significant figures (n in this case).

Syntax to print significant figures 

cout << setprecision(n) << float_variable;

Here, argument n is the number of significant figures that need to be displayed as output.

The following example will illustrate how to print significant figures using the C++ setprecision:

#include <iostream>

#include <iomanip>

using namespace std;

int main() {

  // initialize a floating-point 

  float num = 2.71828;

  cout << "Original number is: " << num;

  cout << "\n";

  // print 3 significant figures

  cout << "The number with 3 significant figures is: ";

  cout << setprecision(3) <<num;

  cout << "\n\n";

  return 0; 

}

Cpp_Setprecision_1.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Decimal Places

The C++ setprecision can also be used to format only the decimal places instead of the whole floating-point or double value. This can be done using the fixed keyword before the setprecision() method. When the fixed keyword is used, the argument in the setprecision() function specifies the number of decimal places to be printed in the output.

Syntax to print a significant number of decimal places

cout << fixed << setprecision(n) << float_variable

Here, argument n is the number of decimal places that need to be displayed as output.

The following example will illustrate how to print significant decimal places using the C++ setprecision and the fixed keyword:

#include <iostream>

#include <iomanip>

using namespace std;

int main() {

  // initialize a floating-point 

  float num = 2.71828;

  cout << "Original number is: " << num;

  cout << "\n";

  // print 3 significant figures

  cout << "The number with 3 significant figures is: ";

  cout << setprecision(3) <<num << endl;

  // print 3 decimal places

  cout << "The number with 3 decimal places is: ";

  cout << fixed << setprecision(3) << num;

  cout << "\n\n";

  return 0;

}

Cpp_Setprecision_2

Preparing Your Blockchain Career for 2024

Free Webinar | 5 Dec, Tuesday | 9 PM ISTRegister Now
Preparing Your Blockchain Career for 2024

Examples of how to use setprecision in C++ 

Example 1: Using setprecision() Function

In this example, we are going to understand the setprecision() function in a well-explained manner by applying the setprecision() function to set a double value to different significant values:

#include <iostream>

#include <iomanip>

#include <ios>

using namespace std;

int main ()

    //Initialising the pi as double

    double pi = 3.141592653589793238;    

    cout<<"Value of pi before setting the precision: "

        <<pi<<endl; 

    cout << "Setting the precision using"

         << " setprecision to 1: "

         << setprecision(1);

    cout << pi << endl; 

    cout << "Setting the precision using"

         << " setprecision to 2: "

         << setprecision(2);

    cout << pi << endl; 

    cout << "Setting the precision using"

         << " setprecision to 5: "

         << setprecision(5);

    cout << pi << endl; 

    cout << "Setting the precision using"

         << " setprecision to 7: "

         << setprecision(7);

    cout << pi << endl; 

    cout << "Setting the precision using"

         << " setprecision to 0: "

         << setprecision(0);

    cout << pi << endl; 

    cout << "Setting the precision using"

         << " setprecision to -1: "

         << setprecision(-1);

    cout << pi << endl; 

    cout << "Setting the precision using"

         << " setprecision to -3: "

         << setprecision(-3);

    cout << pi << endl; 

    return 0;

}

Cpp_Setprecision_3.

In the above code, we are using the setprecision() function to set the precision up to the different numbers of significant digits of pi. For positive numbers 1, 2, 5, and 7, and for 0, the setprecision() function is working fine and giving the desired output. But for negative numbers -1 and -3, it is displaying the default number of significant digits (i.e. 6).

Example 2: Default Precision and Maximum Precision

In this example, we will display the default precision, maximum precision, and set the precision using setprecision() up to a certain significant digit.

#include <iostream>

#include <iomanip>

#include <limits>

using namespace std;

int main ()

{

//initialise pi as double

double pi = 3.141592653589793238; 

//print default precision

cout<< "The default precision in C++ is : \n" 

    << pi << endl; 

//print maximum precision

cout<< "The max precision in C++ is : \n" 

    << setprecision(numeric_limits<double>::digits10 + 1);

cout<< pi << endl; 

//print precision up to 5 significant digits

cout<< "Setting the precision using setprecision() to 5 is : \n" 

    << setprecision(5) 

    << pi << endl; 

return 0;

}

Cpp_Setprecision_4

In the above code, the pi is printed using three different formats. First is the default precision format using the cout, which prints exactly 6 significant digits and truncates all other digits. The second format is printing the maximum significant digits using numeric_limits<double>::digits10. And the third format is printing 5 significant figures using the setprecision() function.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Example 3: Using Fixed to Set Precision in Decimal Places.

In the following example, the fixed keyword is used to set precision in the decimal places.

#include <iostream>

#include <iomanip>

#include <ios>

using namespace std;

int main()

{

    //initialise pi as double

    double pi = 3.141;

    cout << fixed;

    cout << "Value of pi before setting the precision: \n"

        << pi << endl;

    // print setprecision(6)

    cout << "Using setprecision() to set"

        << " the precision to 6: \n"

        << setprecision(6); 

    cout << pi << endl; 

    // print setprecision(8)

    cout << "Using setprecision() to set"

        << " the precision to 8: \n"

        << setprecision(8); 

    cout << pi << endl;

    return 0;

}

Cpp_Setprecision_5. 

In the above program, the fixed keyword is used to print the default precision value of the floating-point variable. This displays 6 decimal digits in the output. Since the variable has only 3 decimal digits in the original value, 0 will be printed for the other 3 places. Similarly, when setprecision(8) is used, it prints 8 significant digits with zeros as the remaining digits.

Example 4: Using Fixed to Find Default Precision and Maximum Precision

In this example, the keyword fixed is used to manipulate the default and maximum precision values.

#include <iostream>

#include <iomanip>

#include <limits>

using namespace std;

int main ()

{

    //initialise pi as double

    double pi = 3.141592; 

    cout<<"Printing Default Precision and Max Precision without fixed \n";

    //print default precision

    cout<< "The default precision in C++ is : \n" 

        << pi << endl;    

    //print maximum precision

    cout<< "The max precision in C++ is : \n" 

        << setprecision(numeric_limits<double>::digits10 + 1);

    cout<< pi << endl; 

    cout<<"Printing Default Precision and Max Precision with fixed \n"; 

    cout<<fixed;

    //print default precision

    cout<< "The default precision in C++ is : \n" 

        << pi << endl;    

    //print maximum precision

    cout<< "The max precision in C++ is : \n" 

        << setprecision(numeric_limits<double>::digits10 + 1);

    cout<< pi << endl;    

    return 0;

}

Cpp_Setprecision_6

In the above program, the original values of the floating-point variable are manipulated using the fixed keyword. First, the default and maximum precision values are printed without using the fixed keyword. And then, the default and maximum precision values are printed with the fixed keyword.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

FAQs

1. What is the SetPrecision function in C++? 

SetPrecision is a function in the C++ standard library's <iomanip> header that is used to set the precision (i.e., the number of decimal places) for floating-point values when using the stream insertion operator (<<) with a std::cout stream.

2. What is the syntax for using the SetPrecision function in C++?

The syntax of the setprecision() function in C++ is : setprecision (int n)

3. Can I use SetPrecision with other stream types? 

SetPrecision can be used with any stream type that supports the stream insertion operator (<<). This includes std::cout, std::cerr, and std::ofstream, among others.

4. Does SetPrecision round the value or truncate it?

The SetPrecision function truncates the value, it does not round it.

5. How to set precision for a particular variable rather than the entire stream? 

You can chain the setprecision function with the variable you want to set precision to.

std::cout<<std::setprecision(5)<<value;

You can also use the manipulator fixed with setprecision to set precision for a particular variable.

std::cout << std::fixed << std::setprecision(5) << value;

6. How can I get the current precision setting of a stream? 

You can use the precision() member function of the stream to get the current precision setting.

std::cout << std::cout.precision();

7. Is it possible to set a global precision for all floating-point values in a program? 

Yes, it is possible to set a global precision for all floating-point values in a program by using the unsetf function to remove the existing precision setting and then using setprecision to set a new one. For example:

std::cout.unsetf(std::ios::floatfield);

std::cout << std::setprecision(5);

This will set a global precision of 5 decimal places for all floating-point values used in the program.

8. Can I use the SetPrecision function with user-defined types?

To use the SetPrecision function with user-defined types, you will need to overload the stream insertion operator (<<) and include the necessary code to handle the precision setting. You can also overload the setprecision function for your user-defined type.

9. Can I set precision for a fixed-point notation? 

Yes, you can set precision for fixed-point notation by using the fixed manipulator in combination with setprecision. This will ensure that the number is displayed in fixed-point notation with the specified number of decimal places. For example:

std::cout << std::fixed << std::setprecision(5) << value << std::endl;

10. Is it possible to set the precision for a numeric string? 

Yes, it is possible to set the precision for a numeric string by using a combination of stringstream and setprecision. You can use stringstream to convert a numeric value to a string and then use setprecision to set the precision of the string. For example:

11. How to set precision in C++ for 2 decimal places?

You can set precision for two decimal places in C++ using the std::setprecision(2) function from the <iomanip> header.

SetPrecision_FAQ_2.

Choose the Right Software Development Program

This table compares various courses offered by Simplilearn, based on several key features and details. The table provides an overview of the courses' duration, skills you will learn, additional benefits, among other important factors, to help learners make an informed decision about which course best suits their needs.

Program NameAutomation Testing Masters ProgramFull Stack Developer - MEAN StackCaltech Coding Bootcamp
GeoAllAllUS
UniversitySimplilearnSimplilearnCaltech
Course Duration11 Months11 Months6 Months
Coding Experience RequiredBasic KnowledgeBasic KnowledgeBasic Knowledge
Skills You Will LearnJava, AWS, API Testing, TDD, etc.HTML, CSS, Express.js, API Testing, etc.Java, JavaScript, Angular, MongoDB, etc.
Additional BenefitsStructured Guidance
Learn From Experts
Hands-on Training
Blended Learning Program
Learn 20+ Tools and Skills
Industry Aligned Projects
Caltech Campus Connect
Career Services
17 CEU Credits
Cost$$$$$$$$
Explore ProgramExplore ProgramExplore Program

Conclusion

In this article, you have learned an important function from the iomanip library called setprecision. You can use this function to specify the number of significant digits in a floating point number that you want to be returned. You saw multiple use-cases of the setprecision function with practical hands-on examples.

To get a better understanding of the C++ programming concepts, you can walk through our tutorial on C++ Programming for Beginners.

To learn more about the important aspects and technologies used in software development, you can opt for the Full Stack Developer - MERN Stack Program provided by Simplilearn. Through this course, you will learn the end-to-end technologies used in professional software development such as DevOps, Agility, Java, CSS, HTML, AWS, etc.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 24 Feb, 2025

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 8 Jan, 2025

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 8 Jan, 2025

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449