
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Printing the correct number of decimal points with cout in C++
When working with floating-point numbers in C++, it's important to know how to control the number of decimal places displayed in the output. By default, cout may not always print the expected number of digits after the decimal point.
How to Print Correct Number of Decimal Points with cout?
To display numbers with a specific number of decimal places using cout, you can use the setprecision() function, which accepts an integer value representing the number of digits after the decimal to be printed and returns a stream manipulator that formats the number with the specified precision. The setprecision() function belongs to the <iomanip>
Syntax
Its syntax is as follows:
setprecision (int num);
Here,
- num: The num represent the new value for decimal precision.
Example
Input: num = 2.3654789d Output: result = 2.4
Explanation:
For 2 significant digits in the number 2.3654789, we identify the first two digits: 2 and 3. The next digit, 6, is ? 5, so we round up the last significant digit (3) to 4.
Example
Input: num = 2.3654789d Output: result = 2.37
Explanation:
For 3 Significant digits (2.3654789), the first three digits are 2, 3, and 6. Since the next digit (5) is >= 5, we round up the last digit (6) to 7.
C++ Example to Print Decimal Precision in cout for Floating-Point
In this example, we use the setprecision() function, which accepts the parameter value as an integer, to set the correct number of decimal point.
#include<iostream> #include<iomanip> using namespace std; int main() { double x = 2.3654789d; cout << "Print up to 3 decimal places: " << setprecision(3) << x << endl; cout << "Print up to 2 decimal places: " << setprecision(2) << x << endl; cout << "Print up to 7 decimal places: " << setprecision(7) << x << endl; return 0; }
The above code produces the following result:
Print up to 3 decimal places: 2.37 Print up to 2 decimal places: 2.4 Print up to 7 decimal places: 2.365479