Reputation: 79
I am working on some c++ problem which should output 22258199.5000000 this number, I have stored the result in double datatype and when I tried to print that variable using std::cout it rounds off to 22258200.0000000, I don't know why is this happening? can anybody explain? what can I do to avoid this problem?
Upvotes: 2
Views: 3681
Reputation: 308101
A 32-bit float
type holds approximately 7 decimal digits, and anything beyond that will be rounded to the nearest representable value.
A 64-bit double
type holds approximately 15 decimal digits and also rounds values beyond that.
Since your value is rounding to the nearest 7-digit number, it appears you're using a float
variable somewhere. Copying a float
value to double
doesn't restore the lost digits.
This doesn't apply to your example, but it might in others - the rounding occurs in binary, not decimal, so you might end up with a value that appears to contain many more digits than I indicated above. Just know that only the first 7 or 15 are going to be accurate in decimal.
Upvotes: 4