0

I'm self learning C++ and for some reason "double" doesn't print more than 6 significant digits even after std::setprecision. Do I need to do something else? Most recent version of codeblocks if that helps. This is all the code:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    std::setprecision(9);
    double A = 654321.987;
    cout << A << endl;
    return 0;
}
  • 1
    Note that 123456e10 123.456 and 123456e-10 all have _6 significant digits_. `654321.987` has 9. – chux - Reinstate Monica Jul 07 '21 at 23:15
  • Try something fun like `setprecision(15)`. That's guaranteed to print 6 significant digits. – Thomas Matthews Jul 07 '21 at 23:16
  • Tactical note: Code::Blocks is a tool that sits atop a separate C++ compiler, so often saying "Most recent Code::Blocks" conveys minimal information. It could be sitting atop an ancient compiler. It could be sitting atop the most recent pull from trunk. On Windows some packages of Code::blocks ship with a mingw-GCC toolchain, and I believe the most-recent official release ships with GCC 8.1. The Cool kids are using GCC 11.1. I'm not so cool, so I'm still using GCC 10.2. And 6.3. And 4.8. And 3.3. – user4581301 Jul 07 '21 at 23:28
  • Yeah. I'm still rocking a 20-year old compiler for one product that just wont die. Frankly I see that as a win. – user4581301 Jul 07 '21 at 23:28
  • Somewhat related: https://stackoverflow.com/a/50970282/4641116 – Eljay Jul 07 '21 at 23:43

1 Answers1

5

You need to feed the result of std::setprecision(9) to std::cout. Otherwise it has no way of knowing what output stream it applies to (and so it won't apply to anything).

std::cout << std::setprecision(9) << A << std::endl;

Or if you prefer you can do it separately:

std::cout << std::setprecision(9);
std::cout << A << std::endl;
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631