[C++]boost::lexical_cast adds extrat digit to cast

Started by
4 comments, last by fpsgamer 15 years, 10 months ago
This is the situation: I have a text file with a line in it: 60.959999 60.959999 I read in the line using fstream and getline. The string that is read in appears to be correct. I then use boost::regex to split up the numbers, and end up with: "60.959999" and "60.959999", as std::strings. This is my code:

std::vector<T> Tokenize( std::string item )
			{
				boost::match_results<std::string::const_iterator> what;
				std::string::const_iterator start = item.begin();
				std::string::const_iterator end = item.end();

				std::vector<T> items;

				while (boost::regex_search(start, end, what, re))
				{
					try
					{
						what[0];
						items.push_back(boost::lexical_cast<T>(what[0]));
					}
					catch (boost::bad_lexical_cast)
					{
						throw std::runtime_error("Bad lexical cast");
					}


					// Update the beginning of the range to the character
					// following the match
					start = what[0].second;
				}

				return items;
			}


I've used this code many times and it works. what contains the two items properly and correctly matches them. However, once I do the lexical_cast<double>, I end up with the two numbers being 60.9599990000003. That three isn't supposed to be there. My regex is "[0-9]+\\.[0-9]+" (double slash for the compiler's sake). I've checked the input file and there are no hidden characters. Everything up to the cast is fine. It seems to be the cast adding 0000003 to my numbers. Any ideas?
Advertisement
That just looks like a precision issue. That is, 60.9599990000003 is the machine number that is closest to 60.959999.
I was thinking that, but 60.959999 should fit into a double just fine, without a loss of precision...shouldn't it?
Quote:Original post by _Sigma
I was thinking that, but 60.959999 should fit into a double just fine, without a loss of precision...shouldn't it?
I tried assigning 60.959999 to a double and got similar results (60.9599990000003, with a bunch more decimal places after the '3').

I'm guessing there just isn't an exact double representation for 60.959999.
Hmmm...well there you go I suppose. Yay binary representation.
Quote:Original post by _Sigma
Hmmm...well there you go I suppose. Yay binary representation.


If you have time, worth a read: What Every Computer Scientist Should Know About Floating-Point Arithmetic

This topic is closed to new replies.

Advertisement