CREW
CREW

Reputation: 936

Why do my float values lose precision and drop decimals? Example code below

I have never used floats really that much before and the current project I am working on requires them. I'm getting weird issues that I learned about years ago but have forgotten why this happens.

My results after multiplying or adding floats aren't what they're supposed to be.

Here is my code:

void main ()
{
    //Example 1 - ERROR
    float a=16937.6;
    float b=112918;
    float total=b+a;
    cout<<total<<endl; //Outputs 129896 - rounds up and loses decimal (129855.6)

    //Example 2 - Error
    float c=247.82;
    float d=9995.2;
    float total2=c+d;
    cout<<total2<<endl; //Outputs 10243 - loses all decimals (10243.02)
    system ("pause");

}

Upvotes: 2

Views: 4658

Answers (2)

D Stanley
D Stanley

Reputation: 152644

Your problem isn't decimal precision - it's the format that is used to output the values.

Try:

cout << setiosflags(ios::fixed) << setprecision(2) << x;

Upvotes: 7

Amadan
Amadan

Reputation: 198526

What Every Programmer Should Know About Floating-Point Arithmetic, or Why don’t my numbers add up?

In short, real numbers are infinite, computers aren't.

Upvotes: 4

Related Questions