C++11 std::to_string(double) - No trailing zeros

前端 未结 9 1791
孤城傲影
孤城傲影 2020-12-01 06:04

Today I tried out some new functions of the C++11 STL and encountered std::to_string.

Lovely, lovely set of functions. Creating a stringstream object fo

相关标签:
9条回答
  • 2020-12-01 06:22

    The C++11 Standard explicitely says (21.5/7):

    Returns: Each function returns a string object holding the character representation of the value of its argument that would be generated by calling sprintf(buf, fmt, val) with a format specifier of "%d", "%u", "%ld", "%lu", "%lld", "%llu", "%f", "%f", or "%Lf", respectively, where buf designates an internal character buffer of sufficient size

    for the functions declared in this order:

    string to_string(int val);
    string to_string(unsigned val);
    string to_string(long val);
    string to_string(unsigned long val);
    string to_string(long long val);
    string to_string(unsigned long long val);
    string to_string(float val);
    string to_string(double val);
    string to_string(long double val);
    

    Thus, you cannot control the formatting of the resulting string.

    0 讨论(0)
  • 2020-12-01 06:29

    With boost::to_string you cannot control the format either but it will output something closer to what you see in the screen. Same with std::lexical_cast<std::string>.

    For a function-like operation with format control, use str(boost::format("...format...")% 0.33).

    What's the difference between std::to_string, boost::to_string, and boost::lexical_cast<std::string>?

    0 讨论(0)
  • 2020-12-01 06:34

    A varied solution to the problem since to_string doesn't work. "The Magic Formula" - my CS2400 teacher

    std::cout.setf(ios::fixed);
    std::cout.setf(ios::showpoint);
    std::cout.precision(2);
    
    const double x = 0.33, y = 42.3748;
    std::cout << "$" << x << std::endl;
    std::cout << "$" << y << std::endl;
    

    Outputs:

    $0.33
    $42.37
    

    any following output you do with decimal numbers will be set as so.

    you can always change the setf and precision as you see fit.

    0 讨论(0)
  • 2020-12-01 06:37

    To leave out the trailing zeros:

    std::ostringstream oss;
    oss << std::setprecision(8) << std::noshowpoint << double;
    std::string str = oss.str();
    

    Hope that helps.

    0 讨论(0)
  • 2020-12-01 06:38

    If all you want to do is remove trailing zeros, well, that's easy.

    std::string str = std::to_string (f);
    str.erase ( str.find_last_not_of('0') + 1, std::string::npos );
    
    0 讨论(0)
  • 2020-12-01 06:39
    double val
    std::wstringstream wss;
    wss << val;
    cout << wss.str().c_str();
    
    0 讨论(0)
提交回复
热议问题