Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert float to std::string in C++

I have a float value that needs to be put into a std::string. How do I convert from float to string?

float val = 2.5; std::string my_val = val; // error here 
like image 705
adam_0 Avatar asked Jan 24 '10 03:01

adam_0


People also ask

Can we convert float to string in C?

gcvt() | Convert float value to string in C This function is used to convert a floating point number to string. Syntax : gcvt (float value, int ndigits, char * buf); float value : It is the float or double value. int ndigits : It is number of digits.

Can we convert float to string?

To convert float to string, use the toString() method. It represents a value in a string.

Which function converts float data to string?

toString() method can also be used to convert the float value to a String. The toString() is the static method of the Float class.


2 Answers

As of C++11, the standard C++ library provides the function std::to_string(arg) with various supported types for arg.

like image 199
dmckee --- ex-moderator kitten Avatar answered Sep 22 '22 02:09

dmckee --- ex-moderator kitten


Unless you're worried about performance, use string streams:

#include <sstream> //..  std::ostringstream ss; ss << myFloat; std::string s(ss.str()); 

If you're okay with Boost, lexical_cast<> is a convenient alternative:

std::string s = boost::lexical_cast<std::string>(myFloat); 

Efficient alternatives are e.g. FastFormat or simply the C-style functions.

like image 30
Georg Fritzsche Avatar answered Sep 24 '22 02:09

Georg Fritzsche