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

前端 未结 9 1792
孤城傲影
孤城傲影 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:42

    std::to_string gives you no control over the format; you get the same result as sprintf with the appropriate format specifier for the type ("%f" in this case).

    If you need more flexibility, then you will need a more flexible formatter - such as std::stringstream.

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

    Create a custom convert function, remove the tailing zeros if necessary.

    //! 2018.05.14 13:19:20 CST
    #include <string>
    #include <sstream>
    #include <iostream>
    using namespace std;
    
    //! Create a custom convert function, remove the tailing zeros if necessary.  
    template<typename T>
    std::string tostring(const T &n) {
        std::ostringstream oss;
        oss << n;
        string s =  oss.str();
        int dotpos = s.find_first_of('.');
        if(dotpos!=std::string::npos){
            int ipos = s.size()-1;
            while(s[ipos]=='0' && ipos>dotpos){
                --ipos;
            }
            s.erase ( ipos + 1, std::string::npos );
        }
        return s;
    }
    
    int main(){
        std::cout<< tostring(1230)<<endl;
        std::cout<< tostring(12.30)<<endl;
    }
    

    The input numbers :

    1230
    12.30
    

    Compile with -std=c++11, then the result:

    1230
    12.3
    
    0 讨论(0)
  • 2020-12-01 06:45

    std::to_string(double) is defined by the standard to just return the same sequence of characters that would be generated by sprintf(buf, "%f", value). No more, no less, especially no way to tweak the format specifier. So no, there is nothing you can do.

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