How to 'Cout' the Correct Number of Decimal Places of a Double Value

Printing the correct number of decimal points with cout

With <iomanip>, you can use std::fixed and std::setprecision

Here is an example

#include <iostream>
#include <iomanip>

int main()
{
double d = 122.345;

std::cout << std::fixed;
std::cout << std::setprecision(2);
std::cout << d;
}

And you will get output

122.34

How to 'cout' the correct number of decimal places of a double value?

Due to the fact the float and double are internally stored in binary, the literal 7.40200133400 actually stands for the number 7.40200133400000037653398976544849574565887451171875

...so how much precision do you really want? :-)

#include <iomanip>    
int main()
{
double x = 7.40200133400;
std::cout << std::setprecision(51) << x << "\n";
}

And yes, this program really prints 7.40200133400000037653398976544849574565887451171875!

How do I print a double value with full precision using cout?

You can set the precision directly on std::cout and use the std::fixed format specifier.

double d = 3.14159265358979;
cout.precision(17);
cout << "Pi: " << fixed << d << endl;

You can #include <limits> to get the maximum precision of a float or double.

#include <limits>

typedef std::numeric_limits< double > dbl;

double d = 3.14159265358979;
cout.precision(dbl::max_digits10);
cout << "Pi: " << d << endl;

c++ cout [double] not printing decimal places

This happens because of the distinction between the default notation and the fixed notation.

According to documentation,

  • Using the default floating-point notation, the precision field specifies the maximum number of meaningful digits to display in total counting both those before and those after the decimal point. Notice that it is not a minimum, and therefore it does not pad the displayed number with trailing zeros if the number can be displayed with less digits than the precision.
  • In both the fixed and scientific notations, the precision field specifies exactly how many digits to display after the decimal point, even if this includes trailing decimal zeros. The digits before the decimal point are not relevant for the precision in this case
    (emphasis is added).

The stream uses the default floating-point notation until (or unless) you switch it to fixed or scientific notation. Since your number has six digit before the decimal point, and the default precision is also set to six, the floating-point numbers look like integers.



Related Topics



Leave a reply



Submit