Round Off error?

I came across the following code
http://www.learncpp.com/cpp-tutorial/25-floating-point-numbers/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>


int main(void)
{
    float fValue1 = 1.345f;
    float fValue2 = 1.123f;
    float fTotal = fValue1 + fValue2; // should be 2.468

    if ( fTotal == 2.468 )
        std::cout << "fTotal is 2.468";
    else
        std::cout << "fTotal is not 2.468";

    std::cout << "\n" << std::setprecision(10) << fTotal << std::endl;

    return 0;
}


Not surprisingly, the result is fTotal is not 2.468, even though it is due to the round off error. the reason is fTotal has been stored as 2.467999935 in the computer. My question is Is there a way to force the computer to store a variable in a limited digits? Let's say in the aforementioned code in four digits so the fTotal should be 2.468?
Use a big number library like http://gmplib.org/
You can't because 2.468 cannot be stored in the amount of space allocated to a float. More specifically, in binary it amounts to:

(All numbers base 2)
1.00111011111001110110110... x 10^1

The ... is where memory space ends, but in order to be perfectly accurate more space is needed. I don't know off hand whether 2.468 repeats in binary, but if it does you're in the same situation.
Topic archived. No new replies allowed.