Thread: Float to string

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    85

    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

  2. #2
    Registered User OnionKnight's Avatar
    Join Date
    Jan 2005
    Posts
    555
    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.
    Last edited by OnionKnight; 02-27-2006 at 09:27 PM.

  3. #3
    Registered User
    Join Date
    Sep 2005
    Posts
    85
    Thank You this worked perfect

  4. #4
    Registered User OnionKnight's Avatar
    Join Date
    Jan 2005
    Posts
    555
    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;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 04:30 PM
  2. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 06:02 AM
  3. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 04:13 PM
  4. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 11:06 PM