View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
C++ Tutorial

Explore C++ Tutorials: Explori…

  • 76 Lessons
  • 15 Hours

Set Precision in C++

Updated on 29/01/2025492 Views

In C++ programming, managing floating-point numbers' precision is significant to achieve accurate and readable outputs. This piece will delve into how you can use set precision in C++, particularly with the std::setprecision() manipulator.

This role is important when you desire to establish the count of decimal locations or the complete number of digits in a floating-point value that will be shown on the output screen. It doesn't matter if you are formatting financial outcomes, scientific information, or any other numeric results; precision aids in achieving clear and exact reports.

What is Set Precision in C++?

In C++, the feature of set precision is a strong tool that helps you to manage how many significant digits come out in floating-point numbers. This setting becomes very important when presenting data in an understandable, brief and arranged form. It is especially useful for scientific, engineering and financial applications where having correct number precision matters a lot.

Precision, in the manner of floating-point numbers, implies the quantity of digits that are utilized for representing a number. In C++, this is not simply related to how many digits emerge after the decimal point; it might signify all significant figures based on context and particular formatting instructions applied.

Role of std::setprecision in C++

The std::setprecision manipulator in C++ is used to determine the precision for floating-point values. This manipulator decides how many digits after the decimal point (or total significant digits) will be shown when converting a floating-point number into a string for outputting purposes.

Using std::setprecision, you are controlling the format of output without changing how the floating-point number is represented internally. This difference is crucial because it signifies that precision setting concerns display and presentation only - it does not affect the accuracy or value in memory of a given floating point number.

How Precision Influences Output

When you use set precision in C++, it is like giving a directive to the output stream (such as std::cout) about how many significant digits should be used for formatting floating-point numbers. This can show itself in different manners:

  1. Total Number of Digits: std::setprecision impacts the overall number of digits shown with default floating-point notation.
  1. Digits After the Decimal: When you use std::fixed along with std::setprecision, it sets the number of digits shown after the decimal point. We use this commonly for money values and other situations where we want to keep the same amount of decimal places.
  1. Scientific Notation: std::setprecision, when used with std::scientific, helps setting the count of digits after decimal point in a number that is formatted as per scientific notation. This is very useful in areas like physics and chemistry where one often encounters very big or small numbers.

How to Use setprecision in C++

If you’re wondering how to use setprecision in C++, let’s guide you through that using simple examples.

To use a specific number of decimal places in C++, you need to add <iomanip> header file. You can then utilize the function std::setprecision() with things like std::cout for managing how many digits after the point are shown. Here is a simple illustration to show this:

Example:

Code:

#include <iostream>
#include <iomanip> // Include for std::setprecision
int main() {
double pi = 3.141592653589793;
std::cout << "Default precision: " << pi << std::endl;
std::cout << "Set precision to 4: " << std::setprecision(4) << pi << std::endl;
return 0;
}

Output:

Default precision: 3.14159
Set precision to 4: 3.142

..Program finished with exit code 0
Press ENTER to exit console.

In this example, the default precision displays the value of pi with as many digits as the stream decides. After setting the precision to 4, the output of pi is truncated to 4 digits in total, including the digits before and after the decimal point.

How to Set Precision in C++ for Double

When working with double values in C++, you can set the precision to control the number of significant digits. Here’s how you can specify the precision for double values:

Example:

Code:

#include <iostream>
#include <iomanip>
int main() {
double value = 123.456789;
std::cout << "Without set precision: " << value << std::endl;
std::cout << "With set precision: " << std::setprecision(6) << value << std::endl;
return 0;
}

Output:

Without set precision: 123.457
With set precision: 123.457

..Program finished with exit code 0
Press ENTER to exit console.

Here, std::setprecision(6) ensures that six digits of the number are displayed, providing a clearer and more controlled output.

How to Use Set Precision in C++ without Count

You may consider setting the precision without directly using cout, particularly when dealing with streams or getting data ready for different kinds of output; this can be done through utilizing std::setprecision() on any object that outputs.

Example:

Code:

#include <iostream>
#include <iomanip>
#include <sstream>
int main() {
std::ostringstream stream;
stream << std::setprecision(5) << 123.456789;
std::cout << "Using stringstream: " << stream.str() << std::endl;
return 0;
}

Output:

Using stringstream: 123.46

..Program finished with exit code 0
Press ENTER to exit console.

In this example, I employ std::ostringstream to give the number a precision of 5. It shows that you can adjust precision not only for std::cout but in other ways too.

Set Precision C++ Example

Here is a comprehensive example to demonstrate set precision in C++ in various scenarios:

Example:

Code:

#include <iostream>
#include <iomanip>
int main() {
double num1 = 3.14159265;
double num2 = 1234.56789;
std::cout << "Original numbers: " << num1 << ", " << num2 << std::endl;
std::cout << "Precision 3: " << std::setprecision(3) << num1 << ", " << std::setprecision(3) << num2 << std::endl;
std::cout << "Precision 5: " << std::setprecision(5) << num1 << ", " << std::setprecision(5) << num2 << std::endl;
std::cout << "Precision 8: " << std::setprecision(8) << num1 << ", " << std::setprecision(8) << num2 << std::endl;
return 0;
}

Output:

Original numbers: 3.14159, 1234.57
Precision 3: 3.14, 1.23e+03
Precision 5: 3.1416, 1234.6
Precision 8: 3.1415927, 1234.5679

..Program finished with exit code 0
Press ENTER to exit console.

In this example, I adjusted the precision for two different numbers to show how it affects both small and large numbers.

Things to keep in mind regarding Set Precision in C++

When you work with set precision in C++, it is important to understand different parts and subtle details. This helps you use the feature well and stay away from usual mistakes. Remember these main things:

1. Always include the <iomanip> header:

The manipulator std::setprecision is located in the <iomanip> header file and not including this file will result in a compilation error.

Example:

#include <iomanip>

2. Precision affects following outputs:

When you apply the precision with std::setprecision, it changes every future output of floating-point numbers in that stream. It implies after setting the precision one time, all following numbers shown will keep this precision until you change it again deliberately.

Example:

std::cout << std::setprecision(4) << 3.14159 << " " << 2.71828 << std::endl;

3. Combine with std::fixed or std::scientific:

To adjust how many numbers come after the decimal, you should use std::fixed with std::setprecision together. This pair decides the digits amount following the dot.

To write numbers in scientific format, you can apply std::scientific along with std::setprecision. This helps to manage how many numbers come after the decimal.

Example:

std::cout << std::fixed << std::setprecision(2) << 123.456 << std::endl; // Outputs 123.46std::cout << std::scientific << std::setprecision(3) << 123.456 << std::endl; // Outputs 1.235e+02

4. Resetting precision:

To get back to the first precision, apply the method std::cout.precision() for obtaining present accuracy level. Keep this number if you plan on returning to former precision afterward.

Example:

int old_precision = std::cout.precision();std::cout << std::setprecision(4) << 3.14159 << std::endl;std::cout.precision(old_precision); // Reset to original

5. Precision and width:

Know how width and precision are not the same. Width is the least characters to show, but precision controls digits after decimal or total important digits.

Here’s how you can set the width:

std::cout << std::setw(10) << std::setprecision(4) << 3.14159 << std::endl; // Outputs " 3.142"

6. Effects on different data types:

The function std::setprecision, it mostly changes how numbers with decimal points (like float, double and long double) are shown. But for whole numbers without decimals - the integers - this function does not do anything.

Using std::setprecision with integers will not change the output.

7. Interaction with other stream manipulators:

Other input/output manipulators, like std::fixed, std::scientific and std::setw, can affect how the function of std::setprecision works.

You must always pay attention to the sequence you use for these tools, because it can change how the result looks.

For example:

std::cout << std::setprecision(2) << std::fixed << 100.12345 << std::endl; // Outputs 100.12

8. Local effects on streams:

When you adjust accuracy with std::setprecision, it only impacts the specific stream where you apply it. Suppose you work with several output streams like std::cout and std::ofstream; in that case, precision must be defined for every single stream on its own.

For instance:

std::ofstream file("output.txt");file << std::setprecision(3) << 3.14159 << std::endl;std::cout << std::setprecision(5) << 3.14159 << std::endl;

These are important starting points to remember, but there is much more to learn beyond this. To discover more and improve your abilities, you can look at the courses upGrad provides for a complete education in software engineering.

To Conclude

To make sure your programs in C++ are easy to understand, you need to be very good at controlling how many important numbers are shown after the decimal point. This helps to show your data correctly and in a way that makes sense. Set precision in C++ comes in particularly handy in this regard.

Keep practicing with various situations and flows to get better at this ability. To improve your skills in software engineering, you might want to look into the Software Engineering Course offered by upGrad and get enrolled soon!

FAQs

1. What is set precision in C++?

In C++, set precision is the way you tell how many important numbers after a decimal point should be shown when you print out floating-point numbers.

2. How do I set precision in C++?

In C++, to define how many digits you want after the decimal, use std::setprecision() from <iomanip> library. It works together with output streams such as std::cout.

3. What does std::setprecision() do?

The function std::setprecision() decides how many numbers after the decimal point or total important digits in floating-point numbers will show.

4. How do I use std::setprecision()?

Include the <iomanip> header and use std::setprecision() with an output stream:

std::cout << std::setprecision(4) << your_float_value;

5. Can you provide an example of setting precision in C++?

Here is an example:

#include <iostream>#include <iomanip>int main() { std::cout << std::setprecision(3) << 3.14159 << std::endl; // Outputs 3.14 return 0;}

6. What if I want to reset the precision after using std::setprecision()?

You can reset the precision by storing the original precision and setting it back later:

int old_precision = std::cout.precision();std::cout << std::setprecision(4) << 3.14159 << std::endl;std::cout.precision(old_precision); // Reset to original
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.