0

I am using C++11. I have real world coordinates such as 38.0098662, 23.7805398 in a text file, meaning 2 double variables. I parse that file with C++ and I convert the strings to double with the stod() method. When I tried printing the values with count.precision(9);, the values seemed to be the same as in the text file.

Then, I want to convert those double values back to string format. For that I use to_string() method. However that seems to be changing the value slightly. For example:

38.0098662, 23.7805398  became
38.009866,  23.780540
// in fact, every number is xx.yyyyyy

I don't understand why this is so hard to do with C++11. Why do I lose precision for no reason ? How can I do this properly ? Every question I looked into pointed to to_string() method, which is what I am using.

dimitris93
  • 4,155
  • 11
  • 50
  • 86
  • _"I have done the exact same thing in python, and I didn't see this behaviour."_ Not sure what the relevance of Python is here. That's a different language entirely. – Lightness Races in Orbit Apr 22 '16 at 14:44

2 Answers2

1

Someone had the same problem as you had. Simply set the precision of the std::ostringstream to your desired size and return it as std::string.

Here is a reference to an older question which shows the implementation:

Look at this!

Hope this helps!

Community
  • 1
  • 1
tistCoder
  • 309
  • 3
  • 12
-3

It cause from compiler code optimization(for fastest run). Sometimes C++ compiler optimizes floating point number processing, and loses a bit precision.