How do i assing a float to a string

How do i assing a float to a string. i have a float number and i want to assing it to a string, how do i do it?
Use a std::stringstream.
http://www.cplusplus.com/reference/iostream/ostringstream/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <sstream>
#include <string>

template <typename ValueType>
std::string stringify( const ValueType& value, int width = 0, int precision = 0, ios_base::fmtflags flags = 0, char fillchar = 0 )
  {
  ostringstream ss;
  if (width > 0) ss.width( width );
  if (precision > 0) ss.precision( precision );
  if (flags != 0) ss.flags( flags );
  if (fillchar != 0) ss.fill( fillchar );
  ss << value;
  return ss.str();
  }

int main()
  {
  float f = 12.7;

  string s = stringify( f, 0, 0, ios::fixed );

  cout << s << endl;

  return 0;
  }

Have fun!
Topic archived. No new replies allowed.