For working professionals
For fresh graduates
More
Explore C++ Tutorials: Explori…
1. The Ultimate C++ Guide: C++ Tutorial for Beginners
2. Application of C++
3. C++ Hello World Program
4. C++ Variable
5. Reference Variable in C++
6. Function Overloading in C++
7. Functions in C++
8. Pointer in C++
9. Data Types in C++
10. C++ for Loop
11. While Loop in C++
12. C++ Lambda
13. Loop in C++
14. Switch Case in C++
15. Array in C++
16. Strings in C++
17. Substring in C++
18. Class and Object in C++
19. Constructor in C++
20. Copy Constructor in C++
21. Destructor in C++
22. Multiple Inheritance in C++
23. Encapsulation in C++
24. Single Inheritance in C++
25. Friend Class in C++
26. Hierarchical Inheritance in C++
27. Virtual Base Class in C++
28. Abstract Class in C++
29. Vector in C++
30. Map in C++
31. Pair in C++
32. Initialize Vector in C++
33. Iterators in C++
34. Queue in C++
35. Priority Queue in C++
36. Stack in C++
37. ifstream in C++
38. Exception Handling in C++
39. Memory Management in C++
40. Templates in C++
41. Type Conversion in C++
42. Enumeration in C++
43. Namespace in C++
44. Set Precision in C++
Now Reading
45. Stringstream in C++
46. Recursion in C++
47. Random Number Generator in C++
48. C++ Shell
49. Setw in C++
50. Multithreading in C++
51. Atoi in C++
52. Call by Value and Call by Reference in C++
53. Difference Between C and C++
54. C# vs C++
55. C++ GUI
56. C++ Game Code
57. Class in C++
58. C++ Header Files
59. Power Function in C++
60. Data Hiding in C++
61. Inline Function in C++
62. Getline Function in C++
63. Cin in C++
64. Printf in C++
65. Struct in C++
66. C++ List
67. static_cast in C++
68. C++ Comments
69. Structures in C++
70. C++ Standard Template Library (STL)
71. Virtual Function in C++
72. Sorting in C++
73. Polymorphism in C++
74. Oops Concepts in C++
75. Converting Integers to Strings in C++
76. Differences Between Break and Continue
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.
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.
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.
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:
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.
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.
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.
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.
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 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!
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
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
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.