Pregunta

I am working in C++ and having issues with the precision of reading in a double

input_file>>temp_double;

the number in the file is something like 1234.567 but when it reads in, it reads as 1234.56699999999. So how can I get it to read as it is in the file, I use the amount of decimals in later functions so I need it to be proper. the numbers in the file range from 3-5 decimal places

¿Fue útil?

Solución 2

float and double store their data using an IEEE standard that stores a sign bit, an exponent, and a fractional value. Most decimal values will not be exactly precise when stored due to the base 10 to base 2 conversion of the fractional portion.

Also, mathematically, 1234.566999999999999.... = 1234.567

Otros consejos

As others have said, a double cannot represent many decimal values precisely. It stores its data in binary, and rounds off eventually. Many numbers which can be represented precisely in decimal have non-terminating representations in binary.

If you need precise representation, look at e.g Boost::Multiprecision.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top