C++ Decimal Precision
Decimal Precision
When you print a decimal number with cout, the output does not always look the way you expect. For example, 9.0 is printed as 9:
Example
double x = 9.0;
double y = 19.990;
double z = 3.14159265;
cout << x << "\n"; // 9
cout << y << "\n"; // 19.99
cout << z << "\n"; // 3.14159
This is because cout uses these rules by default:
- It shows at most 6 digits in total (before and after the decimal point), and rounds the rest.
- It removes zeros at the end of the decimals. If only zeros are left, the decimal point is removed too.
The value itself is not changed. x still holds 9.0. Only the way it is printed is different.
Note: Very large numbers are printed in scientific notation. For example, 1234567.0 is printed as 1.23457e+06, which means 1.23457 times 106.
Set Decimal Precision
To choose how many decimals are shown, use fixed and setprecision(). setprecision() is found in the <iomanip> library.
Note: This is the first time we use a library other than <iostream>. In the Syntax chapter, you learned that #include <iostream> lets you use cout. In the same way, #include <iomanip> lets you use setprecision(). Add it at the top of your program, below #include <iostream>:
Example
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double x = 9;
double y = 9.5;
cout << fixed << setprecision(2);
cout << x << "\n"; // 9.00
cout << y << "\n"; // 9.50
return 0;
}
fixed means "always show a fixed number of decimals", and setprecision(2) sets that number to 2. Now 9 is printed as 9.00, which is useful for things like prices.
Note: fixed and setprecision() keep working for all the numbers you print after them, not only the first one.
Rounding
setprecision() does not just cut off the extra digits. It rounds the number to the nearest value:
Example
double myNum = 3.14159;
cout << fixed << setprecision(2) << myNum << "\n"; // 3.14
cout << fixed << setprecision(3) << myNum << "\n"; // 3.142 (rounded up)
cout << fixed << setprecision(0) << myNum << "\n"; // 3
setprecision() Without fixed
If you use setprecision() without fixed, the number sets how many digits are shown in total, not only after the decimal point:
Example
double myNum = 3.14159;
cout << setprecision(3) << myNum; // 3.14 (3 digits in total)
This is easy to mix up. If you want a number of decimals, like for a price, always use fixed together with setprecision().
Visualize Decimal Precision
Choose an option below to see how 3.14159 is printed:
Code
Output
Explanation