Convert float to std::string in C++

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

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

    std::array 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.

提交回复
热议问题