Reputation: 691
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.
Upvotes: 10
Views: 13868
Reputation: 68638
On linux you can use __float128 which is a quadruple precision floating point type.
Upvotes: 2
Reputation: 254461
The most commonly used double precision format stores the number with 53 bits of precision. This gives approximately 16 decimal digits of precision.
You may find that long double
gives more precision, but there is no guarantee that that is any larger than double
.
If you need more precision than you can get from native machine types, you will need a high-precision numeric library, such as GMP.
Upvotes: 2
Reputation: 7688
C++ uses IEEE floating point types which are only precise to a certain degree by design. If you need arbitary precision take a look at eg GNU MP Bignum or any other arbitary precision library.
Upvotes: 6
Reputation: 490128
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.
Upvotes: 8