C++: what is the optimal way to convert a double to a string?

后端 未结 12 1765
温柔的废话
温柔的废话 2020-12-16 17:09

What is the most optimal way to achieve the same as this?

void foo(double floatValue, char* stringResult)
{
    sprintf(stringResult, \"%f\", floatV         


        
相关标签:
12条回答
  • 2020-12-16 17:37

    I'd say sprintf is pretty much the optimal way. You may prefer snprintf over it, but it doesn't have much to do with performance.

    0 讨论(0)
  • 2020-12-16 17:41

    If you use the Qt4 frame work you could go :

    double d = 5.5;
    QString num = QString::number(d);
    
    0 讨论(0)
  • 2020-12-16 17:41

    In the future, you can use std::to_chars to write code like https://godbolt.org/z/cEO4Sd . Unfortunately, only VS2017 and VS2019 support part of this functionality...

    #include <iostream>
    #include <charconv>
    #include <system_error>
    #include <string_view>
    #include <array>
    
    int main()
    {
        std::array<char, 10> chars;
        auto [parsed, error] = std::to_chars(
            chars.data(), 
            chars.data() + chars.size(), 
            static_cast<double>(12345.234)
        );
        std::cout << std::string_view(chars.data(), parsed - chars.data());
    }
    

    For a lengthy discussion on MSVC details, see https://www.reddit.com/r/cpp/comments/a2mpaj/how_to_use_the_newest_c_string_conversion/eazo82q/

    0 讨论(0)
  • 2020-12-16 17:42

    http://www.cplusplus.com/reference/iostream/stringstream/

    double d=123.456;
    stringstream s;
    s << d; // insert d into s
    
    0 讨论(0)
  • 2020-12-16 17:46

    I'd probably go with what you suggested in your question, since there's no built-in ftoa() function and sprintf gives you control over the format. A google search for "ftoa asm" yields some possibly useful results, but I'm not sure you want to go that far.

    0 讨论(0)
  • 2020-12-16 17:47

    The best thing to do would be to build a simple templatized function to convert any streamable type into a string. Here's the way I do it:

    #include <sstream>
    #include <string>
    
    template <typename T>
    const std::string to_string(const T& data)
    {
       std::ostringstream conv;
       conv << data;
       return conv.str();
    }
    

    If you want a const char* representation, simply substitute conv.str().c_str() in the above.

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