-
Float to string
Hello;
I have a float in the variable
float x_lab;
I need to convert this value to a string and store the string as a variable for later use. The precision needs to be to two decimal places .. positive or negative values could be in x_lab. And x_lab may change and be output through the string later in the program. I must convert to a string, b/c i will actually be passing the string to an openGL call.
Please help. I need the fastest and simplest way to do this
Thanks
-
char buf[asmuchasyouneed];
sprintf(buf, "%.2f", x_lab);
[edit] oops, forgot this was the C++ forum.
Code:
#include <string>
#include <sstream>
string str;
stringstream stream(str, ios_base::out);
stream.precision(2);
stream << x_lab;
I think this might work but it's late so someone else has to take over for me.
-
Thank You this worked perfect
-
Are you sure? The first one does, but I looked up my stringstream version and it seems I was way off. Here's a valid code example to clean up my mess:
Code:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
float x_lab = 5.24;
ostringstream stream;
stream.precision(2);
stream << fixed << x_lab;
cout << stream.str();
return 0;
}