- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the precision of floating point in C++?
In C++, the size of the floating point number is either 4-byte or 8-bytes. So it can store up to few decimal places. For example, the 1/3 = 0.333333…… Up to infinity. If we store it inside floating type variable, then it will store some significant digits. The default value is 6. So normally floating point numbers in C++ can display up to 6 decimal places.
We can change the size of the precision using setprecision. This is present inside the iomanip header file. Let us see one example to get the idea.
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