0

Why is it that in C++, the showpoint manipulator only has a limit of six significant figures? If anything is beyond six figures, weird things happen. Here's what got me into this question:

int main()
    {
        double x = 1.345;
        cout << showpoint << x << endl;

        return 0;
    }

Output: 1.34500

Which is totally fine, as expected. However, if I were to do something like this, where I exceed the six significant figure limit, weird things happen with the output:

int main()
    {
        double x = 1.345678;
        cout << showpoint << x << endl;

        return 0;
    }

Output: 1.34568

Notice that the 7 is missing, and seems to be replaced by 8. Because by right, our x is initialized with 1.345678. So, we should, instead, get 1.345678, but no. So why is it like that?

Any thoughts?

ken_you_not
  • 93
  • 1
  • 1
  • 11
  • 3
    Checkout http://www.cplusplus.com/reference/ios/showpoint/. Looks like you need to change `cout.precision(8)` as it appears to default to 7. – Mark Jun 29 '18 at 00:07
  • 6
    It's not skipping the 7 to output 8. It's rounding the last two digits (78) up to 80, and then truncating (dropping) the final 0. – Ken White Jun 29 '18 at 00:12
  • Hi Ken, thank you for the clarification. Just to make sure I get what you mean, are you saying that if a floating-point number has more than six significant figures, c++ will take the first or first few of the 'excess' numbers to round off to the sixth figure. Which, in my case, is an 8, so the sixth figure, '7' will be rounded to '8', hence the output. – ken_you_not Jun 29 '18 at 00:44
  • Also, I found out that coincidentally, if the sixth digit were to be a '9' before the rounding off of excess figures, c++ will round it off too. Same goes for the respective figures from right to left, leaving trails of zeros behind while remaining itself as a total of significant figures. Which means, if there is a number like 1.499997, rounding it off with showpoint will leave it to be 1.50000 – ken_you_not Jun 29 '18 at 00:48
  • 1
    Correct, that is how rounding often works. Although there are several different rounding strategies. For an example of precision in C++: https://stackoverflow.com/questions/50968737/comparison-of-double-long-double-float-and-float128 – Eljay Jun 29 '18 at 01:00
  • It's not that "C++ will take...". It's what the **stream inserter** does. The stream inserters for floating-point values by default show six significant digits. If you want something different you have to say so; that's what `std::setprecision` (and the member function `precision`) is for. – Pete Becker Jun 29 '18 at 11:06

0 Answers0