Convert double to string using boost::lexical_cast in C++?

后端 未结 4 520
走了就别回头了
走了就别回头了 2020-12-05 19:41

I\' d like to use lexical_cast to convert a float to a string. Usually it works fine, but I have some problems with numbers without decimal. How can I fix numbe

4条回答
  •  既然无缘
    2020-12-05 20:18

    From the documentation for boost lexical_cast:

    For more involved conversions, such as where precision or formatting need tighter control than is offered by the default behavior of lexical_cast, the conventional stringstream approach is recommended. Where the conversions are numeric to numeric, numeric_cast may offer more reasonable behavior than lexical_cast.

    Example:

    #include 
    #include 
    
    int main() {
        std::ostringstream ss;
        double x = 5;
        ss << std::fixed << std::setprecision(2);
        ss << x;
        std::string s = ss.str();
        return 0;
    }
    

提交回复
热议问题