Stéphane
Stéphane

Reputation: 20340

How can I get the exact value of a double?

I have a situation where:

void foo( const double d )
{
    const double rounded_2_decimals = std::round(d*100.0) / 100.0;
    std::cout << "d=" << d << std::endl;
    std::cout << "r=" << rounded_2_decimals << std::endl;
}

When printed, d=3.125, but r=3.12 instead of r=3.13.

I suspect that is because the passed in d is actually 3.1249999.... This is why I put in the initial cout, so I could see the "true" value being passed in. Does std::cout round values before it displays them? How else could I see the "real" value being passed in?

Upvotes: 0

Views: 1410

Answers (1)

ccoder83
ccoder83

Reputation: 504

Yes, std::cout does round values, however you can set a higher precision. First include the iomanip header. Then:

void foo( const double d )
{
    const double rounded_2_decimals = std::round(d*100.0) / 100.0;
    std::cout << "d=" << std::setprecision(9) <<  d << std::endl;
    std::cout << "r=" << std::setprecision(9) << rounded_2_decimals << std::endl;
}

Live example program here

Upvotes: 2

Related Questions