How to avoid rounding off of large float or double

2019-08-12 18:22发布

问题:

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?

回答1:

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.