How to output float to cout without scientific notation or trailing zeros?

后端 未结 3 1965
谎友^
谎友^ 2020-12-06 12:25

What is the most elegant way to output a floating point number in C++ with no scientific notation or trailing zeros?

         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 13:10

    the other example like mine actually output "200." or did "200" >> "2".

    this should work for everything (as I took it from a string to val function I use).

    string fix(float in) {       
        string s = to_string(in);
        size_t dot = s.find_first_of('.'), last = s.find_last_not_of(".0");
    
        if (dot!=string::npos) return s.substr(0, max(dot,last+1));
        else return s;
    }
    

提交回复
热议问题