0

Disclaimer: I am a new C++ programmer, but I have read a lot about floating point numbers and the like and how some numbers can't be stored properly and all of that. I haven't been able to find anything really speaking specifically to this issue in my many Google searches.

Ok, so basically what the title says - I'm having an issue when I concatenate two double variables into a string, they drop one decimal at the end of each variable number. What I'm doing is having the user enter in two numbers (stored as doubles) for some calculation, but later on in the program I need the two numbers to be in a string so I can search for them in an array (which I have already loaded values into). When these numbers get concatenated into a string they drop the last digit in both their values, which throws off the search (I did some debugging to find this issue).

Here are what my variables read as right after they are assigned their value by the user:

user1 = 43.5803481
user2 = -116.7406331

So far so good with these values, here's what it looks like after I concatenate them:

concat = 43.580348 -116.740633

As you can see I lose the 1 at the end of each variable.

Here's the code I'm using to concatenate them:

concat = to_string(user1) + " " + to_string(user2);

I have already declared the variable concat as a string and everything.

So I guess I'm wondering:
(1) Why is it doing this? (see edit)
(2) How do I fix it? (is there a better way to do this? etc.)

Thanks in advance for looking at this!

EDIT: I now understand that to_string only carries six decimal places, but solutions on other pages that have been linked have not seemed to fix my issue.

Oryn
  • 5
  • 1
  • 6
  • possible duplicate of [Set precision of std::to\_string when converting floating point values](http://stackoverflow.com/questions/16605967/set-precision-of-stdto-string-when-converting-floating-point-values) – OldProgrammer Apr 05 '15 at 04:28
  • Thanks, I didn't know the to_string() only took 6 decimal places. Now I just have to figure out what that code in the link actually means/does. – Oryn Apr 05 '15 at 04:44
  • possible duplicate of [The precision of std::to\_string(double)](http://stackoverflow.com/questions/14520309/the-precision-of-stdto-stringdouble) – Alexis Wilke Apr 05 '15 at 06:25

1 Answers1

0

I ended up using the code below and it did exactly what I needed it to - it took a double variable and changed it into a string, while keeping the precision.

Note: For documentation purposes, you will need to include #include <sstream> to your preprocessor for this to work.

template <class T>
string num2str(const T& num, unsigned int prec = 8) 
{
string ret;
stringstream ss;


ios_base::fmtflags ff = ss.flags();
ff |= ios_base::dec;
ff |= ios_base::fixed;
ff |= ios_base::basefield;
ss.flags(ff);
ss.precision(prec);
ss << num;
ret = ss.str();
return ret;
};
Oryn
  • 5
  • 1
  • 6