SetPrecision Function in C++

SetPrecision Function in C++

Have you ever tried printing a float in C++ and getting unexpected outputs without a decimal place or round-off? The function setprecision() in C++ is used to display numbers, but it is not as straightforward as it appears. Should it be used with fixed? Does it affect the significant figures? In this article, all these confusions will be solved with examples, best practices, and real-world applications, with setprecision meant for the correct formatting of floating-point output.

Table of Contents:

What is the setprecision Function in C++?

The setprecision() function is a manipulator in C++ defined in the header <iomanip>. This manipulator controls how many digits will be displayed for floating-point numbers when they go to output streams like cout. Depending also on the formatting, it considers the total number of significant digits or counts only the number of digits after the decimal.

Syntax of C++ setprecision

#include <iomanip>
std::cout << std::setprecision(n);

In C++, the manipulators declared in the #include <iomanip> header, like std::setprecision(), are used for the output formatting. The statement std::cout << std::setprecision(n); sets the total number of significant digits printed for floating-point numbers. This is helpful when trying to control output precision for calculations in either the scientific or financial fields.

Parameters of C++ iomanip::setprecision() Function

  • n (int): Specifies the number of digits to show.
  • If fixed is not used, it sets the total number of significant digits.
  • If fixed is used, it sets the number of digits after the decimal point.

How Does C++ iomanip::setprecision() Function Work

  1. This is a manipulator that goes under the name std::setprecision(n) along with the standard header <iomanip> and is used with output streams like std::cout.
  2. Without using std::fixed, it controls the total number of significant digits, which is both before and after the decimal point.
  3. When you use it with std::fixed, then it controls the number of digits that go after the decimal point; this is the most appropriate way to format monetary or scientific data.
  4. This just affects the format of the output of numbers, not the actual way they are stored in memory.
  5. It can be combined with other manipulators such as std::scientific, std::showpoint, or std::setw in the name of their extended formatting.
  6. std::setprecision() will be in effect for all future floating-point outputs on the same stream until it is modified. 
  7. That’s commonly used to improve the readability of outputs or to comply with certain output standards.

Significant Figures and Decimal Places

1. Significant Figures 

In the absence of std::fixed in respect to std::setprecision(n), it refers to the total number of significant digits that can be shown for a floating-point number. Here, significant digits include all digits about the number before or after the decimal point, depending on the magnitude of the value. 

Example: 

Cpp

Output: 

Significant Figures 

Using a setprecision gives you five significant figures displayed. The effect is a restriction of 5 on the output. Therefore, something like 123.456789 is shown in the five significant digits as 123.46.

2. Decimal Places

The std::setprecision(n) uses the format to control the number of digits after the decimal point for output from floating-point numbers after std::fixed has been invoked. This means that the size of the number is irrelevant.

Example: 

Cpp

Output: 

Decimal Places

The above code is set up for exactly three decimal points, which means that the number will be displayed as 123.457, but in terms of modified rounding, it will look like this when rounded to the third decimal place. This C++ program uses std::fixed with std::setprecision(3) to format the floating-point number num.

Where and How Can We Use setprecision in C++?

setprecision is used to format floating-point output, for example, in scientific calculations, financial reports, and user interfaces. setprecision can be combined with other manipulators, including fixed, scientific, and showpoint, to offer precise control over output. 

This control is crucial for settings of ultimate accuracy and fine presentation, such as when two decimal places must be displayed for currency values or presenting scientific data in exponential form. It also plays a role in standardizing output for logging, debugging, and exporting data into external files such as CSV or JSON, where consistent precision is required.

Methods to Use SetPrecision in C++

Below are a few methods to use setprecision() in C++:

Method 1: Using setprecision() for Significant Digits

This instance explains how std::setprecision(4) limits the output to 4 significant digits. When std::fixed is not used, the formatting affects the total number of significant digits in the number, not just the digits after the decimal point.

Example: 

Cpp

Output: 

Method 1: Using setprecision() for Significant Digits

setprecision(4) is just an example that limits the output of a floating-point number to 4 significant digits. This is useful when one wants to round to a certain number of total digits, irrespective of the position of the decimal.

Method 2: Default and Maximum Precision Without Fixed

Floating points are printed with a default of 6 significant digits. Using std::setprecision(15) displays almost full double precision (15-16 digits) and thus enhances the numeric output accuracy for high precision needs. 

Example: 

Cpp

Output: 

Method 2: Default and Maximum Precision Without Fixed

Floating-point numbers are displayed with 6-digit precision by default in C++. setprecision(15) gives all double-precision indications, reasonable for scientific or very precise numerical data.

Method 3: Using fixed with setprecision() for Decimal Places

It sets std::fixed imposed with std::setprecision(3) to print the output to 3 digits right of the decimal. Generally, currency or fixed-point display with required decimal consistency needs this kind of formatting.

Example: 

Cpp

Output: 

Method 3: Using fixed with setprecision() for Decimal Places

Here, fixed along with setprecision(3) shows exactly 3 digits after the decimal point. This would be a good choice when one wants to format currency or control decimal presentation in a report. 

Method 4: Default vs Custom Decimal Places with fixed

The example shows how the default behavior with std::fixed prints a total of 6 decimal places. Modifying this to setprecision(10) will extend the decimal places to 10, hence providing finer control over output precision.

Example: 

Cpp

Output: 

Method 4: Default vs Custom Decimal Places with fixed

Fixed by itself will show 6 decimal points by default in C++, while when combined with setprecision(10), it extends the decimal display. This shows how to control and extend decimal precision in fixed-point format.

Get 100% Hike!

Master Most in Demand Skills Now!

Difference between std::setprecision() with and without std::fixed in C++

Feature Without std::fixed With std::fixed
Purpose Sets the total significant digits to display. Sets the number of decimal places to display.
Affects Impacts the number of digits shown both before and after the decimal point. Affects only the digits after the decimal point.
Example std::cout << std::setprecision(4) << 123.456789; std::cout << std::fixed << std::setprecision(3) << 123.456789;
Output (for 123.456789) 123.5 (4 significant digits) 123.457 (3 decimal places)
Rounding Behavior Rounds are based on the total number of significant digits. Rounds are based on the number of decimal places specified.
Precision Type Affects the total significant digits (both integer and fractional parts). Affects only the fractional part of the number.
Use Case When you need control over significant digits for various kinds of data. When you need control over decimal places in floating-point values.

Formatting Currency Output Using setprecision

In C++, for formatting prices, salaries, or invoice totals to have exactly two decimal places, the std::fixed manipulator should be used along with std::setprecision(2). This ensures that the output is displayed in the same format, for example, for currencies; thus, having exactly two digits behind the decimal point is needed for correctness and clarity. Important in all financial applications, such formatting of currency is relevant because it is possible to obtain different displays for currency values, depending on the number of decimal places in the actual number.

Example: 

Cpp

Output: 

Formatting Currency Output Using setprecision

In this program, the variables price and salary are both floating-point numbers formatted to display two digits after the decimal point using fixed and setprecision(2). This method is often used in applications that deal with finance and display currency values in a consistent and user-friendly manner.

Real-World Projects Using setprecision

In practical projects, std::setprecision() will help you in producing neat and clear, and most importantly, professionally formatted output. It is particularly important in a case where you want to show decimal results-for example, body measurements or financial figures-where consistency and accuracy play an important role.

Example: 

Cpp

Output: 

Real-World Projects Using setprecision

setprecision(2) and fixed are used to display currency correctly, which has to have two decimal places.

Conclusion

In C++, the std::setprecision() manipulator provides precise control over number formatting in output streams. This allows for display of either the significant digits or the decimal places, thereby enhancing the lucidity, correctness, and professionalism of your program’s output. Particularly, this is very useful for financial calculators, scientific working tools, and reports with a given format.

SetPrecision Function in C++ – FAQs

Q1. What does std::setprecision() do in C++?

This manipulator controls the number of digits that appear in the output for floating-point values.

Q2. Which header file is required for setprecision()?

The header file is required for setprecision().

Q3. Does setprecision() affect how numbers are stored in memory?

No, it only has a role in displaying a format for numbers, but it does not alter the inner storage mechanism.

Q4. What’s the difference between setprecision() with and without fixed?

Without fixed, it sets the number of significant digits; with fixed, it sets the number of digits after the decimal.

Q5. Can setprecision() be combined with other manipulators?

For formatting, it can be combined with fixed, scientific, setw, and others.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner