
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 Correct Number of Decimal Points with cout in C++
Here we will see how to print some floating point numbers up to some pre-defined decimal places. In C++, we can use setprecision with the cout to do this word. This is present under the iomanip header file in C++.
Example Code
#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; }
Output
Print up to 3 decimal places: 2.365 Print up to 2 decimal places: 2.37 Print up to 7 decimal places: 2.3654789
Advertisements