Christian
Christian

Reputation: 831

Why does cout.precision() increase floating-point's precision?

I understand that single floating-point numbers have the precision of about 6 digits, so it's not surprising that the following program will output 2.

#include<iostream>
using namespace std;

int main(void) {
    //cout.precision(7);

    float f = 1.999998; //this number gets rounded up to the nearest hundred thousandths
    cout << f << endl;  //so f should equal 2

    return 0;
}

But when cout.precision(7) is included, in fact anywhere before cout << f << endl;, the program outputs the whole 1.999998. This could only mean that f stored the whole floating-point number without rounding, right?

I know that cout.precision() should not, in any way, affect floating-point storage. Is there an explanation for this behavior? Or is it just on my machine?

Upvotes: 0

Views: 1463

Answers (3)

user207421
user207421

Reputation: 311008

I understand that single floating-point numbers have the precision of about 6 digits

About six decimal digits, or exactly 23 binary digits.

this number gets rounded up to the nearest hundred thousand

No it doesn't. It gets rounded to the nearest 23 binary digits. Not the same thing, and not commensurable with it.

Why does cout.precision() increase floating-point's precision?

It doesn't. It affects how it is printed.

Upvotes: 2

andy1633
andy1633

Reputation: 58

The default precision for std::cout is 6 according to this and your number is 7 digits long including the parts before and after the decimal place. Therefore when you set precision to 7, there is enough precision to represent your number but when you don't set the precision, rounding is performed.

Remember this only affects how the numbers are displayed, not how they are stored. Investigate IEEE floating point if you are interested in learning how floating point numbers are stored.

Try changing the number before the decimal place to see how it affects the rounding e.g float f = 10.9998 and float f = 10.99998

Upvotes: 0

Rene
Rene

Reputation: 2466

As already written in the comments: The number is stored in binary.

cout.setprecision() actually does not affect the storage of the floating point value, it affects only the output precision.

Upvotes: 0

Related Questions