# C++ double accuracy in C++

## Recommended Posts

a simple assignment such as bellow

    int main()
{
double variable = 1.4;
double value = variable;
return 0;
}

the value of both variable and value is 1.399999999999999

Why is this?

BUT when setting this

double value = 1.5;

Gives correct result!! why?

Any idea on how to resolve this or atleast a workaround?

##### Share on other sites

There is infinite real numbers, while double can only present finite numbers, so it can't present all numbers.

To solve it, you need fixed point number

##### Share on other sites
3 hours ago, cebugdev said:

Any idea on how to resolve this or atleast a workaround?

As others have noted this is a function of the fact that certain real numbers can not be represented in binary with an exact representation the same as they can in decimal. However in most cases this isn't so critical. For instance if you were to print out 1.4 using printf("%3.1f",1.4) , it will generally give you what you want (i.e. 1.4) even though the internal representation is closer to 1.399999999999999 . Basically your problem is with formatting. So your GUI needs to have some option to do the appropriate formatting on output. Baring that, you can use sprintf or the C++ stream equivalent to format your number and convert it to a string before handing it to your GUI.

If you really need to store 1.4 exactly you would probably have to use something like BCD. Binary Coded Decimal .  As I recall old 16 bit intel CPUs had some machine language opcodes to help support BCD but I'm not sure if it was carried forward in later architectures. I'm guessing that's not what you really need anyway.

##### Share on other sites

Just to add that, this is not unique to C++. Anything that uses (binary) floating point decimal will display this kind of problem. In fact, this is by-design.

##### Share on other sites

It's not even a matter of design, it's an inherent property of representing fractions with a finite number of digits. A rational non-integer number can only be accurately represented with a finite number of digits if all the prime factors of the denominator are also prime factors of the radix; otherwise, it requires an infinitely repeating digit sequence.

## Create an account or sign in to comment

You need to be a member in order to leave a comment

## Create an account

Sign up for a new account in our community. It's easy!

Register a new account

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

(You must login to your GameDev.net account.)

• 10
• 11
• 13
• 9
• 11
• ### Forum Statistics

• Total Topics
634090
• Total Posts
3015430
×