Convert float to std::string in C++

前端 未结 8 1955
后悔当初
后悔当初 2020-11-29 02:23

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;          


        
相关标签:
8条回答
  • 2020-11-29 03:12

    This tutorial gives a simple, yet elegant, solution, which i transcribe:

    #include <sstream>
    #include <string>
    #include <stdexcept>
    
    class BadConversion : public std::runtime_error {
    public:
      BadConversion(std::string const& s)
        : std::runtime_error(s)
        { }
    };
    
    inline std::string stringify(double x)
    {
      std::ostringstream o;
      if (!(o << x))
        throw BadConversion("stringify(double)");
      return o.str();
    }
    ...
    std::string my_val = stringify(val);
    
    0 讨论(0)
  • 2020-11-29 03:17

    You can use std::to_string in C++11

    float val = 2.5;
    std::string my_val = std::to_string(val);
    
    0 讨论(0)
  • 2020-11-29 03:19

    You can define a template which will work not only just with doubles, but with other types as well.

    template <typename T> string tostr(const T& t) { 
       ostringstream os; 
       os<<t; 
       return os.str(); 
    } 
    

    Then you can use it for other types.

    double x = 14.4;
    int y = 21;
    
    string sx = tostr(x);
    string sy = tostr(y);
    
    0 讨论(0)
  • 2020-11-29 03:19

    If you're worried about performance, check out the Boost::lexical_cast library.

    0 讨论(0)
  • 2020-11-29 03:20

    Use std::to_chars once your standard library provides it:

    std::array<char, 32> buf;
    auto result = std::to_chars(buf.data(), buf.data() + buf.size(), val);
    if (result.ec == std::errc()) {
      auto str = std::string(buf.data(), result.ptr - buf.data());
      // use the string
    } else {
      // handle the error
    }
    

    The advantages of this method are:

    • It is locale-independent, preventing bugs when writing data into formats such as JSON that require '.' as a decimal point
    • It provides shortest decimal representation with round trip guarantees
    • It is potentially more efficient than other standard methods because it doesn't use the locale and doesn't require allocation

    Unfortunately std::to_string is of limited utility with floating point because it uses the fixed representation, rounding small values to zero and producing long strings for large values, e.g.

    auto s1 = std::to_string(1e+40);
    // s1 == 10000000000000000303786028427003666890752.000000
    
    auto s2 = std::to_string(1e-40);
    // s2 == 0.000000
    

    C++20 might get a more convenient std::format API with the same benefits as std::to_chars if the P0645 standards proposal gets approved.

    0 讨论(0)
  • 2020-11-29 03:24

    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.

    0 讨论(0)
提交回复
热议问题