Jump to content
  • Advertisement
Sign in to follow this  
_Sigma

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

This topic is 3656 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
Advertisement
That just looks like a precision issue. That is, 60.9599990000003 is the machine number that is closest to 60.959999.

Share this post


Link to post
Share on other sites
I was thinking that, but 60.959999 should fit into a double just fine, without a loss of precision...shouldn't it?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!