简体   繁体   中英

How to avoid rounding off of large float or double values?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM