Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Precision loss with double C++

Tags:

c++

I'm developing a C++ application that runs on linux environment. I need to store a large value with 6 decimal places. I used a double for that, but after assigning it, it didn't contain the exact value. It was rounded off.

Ex:

double dValue = 79447461534242.913072; //Assignement of value

But after doing that , whenever I see the value of dValue, it is something like 79447461534242.906

Can some one let me know why this is happening and suggest me the correct data type which can hold the exact value without losing any precision.

like image 278
Anupama Pathirage Avatar asked Aug 23 '12 17:08

Anupama Pathirage


2 Answers

In a typical implementation, a double has about 15 digits of precision total. It doesn't matter much whether those are before or after the decimal point, it's just a total of 15 digits.

In your case, the original number is about 20 digits, so five are lost immediately.

like image 124
Jerry Coffin Avatar answered Oct 18 '22 17:10

Jerry Coffin


On linux you can use __float128 which is a quadruple precision floating point type.

like image 32
Andrew Tomazos Avatar answered Oct 18 '22 16:10

Andrew Tomazos