Convert float to std::string in C++

前端 未结 8 2004
后悔当初
后悔当初 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:24

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

    #include 
    //..
    
    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(myFloat);
    

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

提交回复
热议问题