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

后端 未结 3 1955
谎友^
谎友^ 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:02

    If string manipulating doesn't hurt your eyes:

    std::string fixedfloat(float x)
    {
        std::ostringstream ss;
        ss << std::fixed << std::setprecision(std::cout.precision()) << x;
        std::string str = ss.str();
        return str.substr(0, str.find_last_not_of('0') + 1);
    }
    
    int main()
    {
        float b = 0.1f;
    
        std::cout << std::setprecision(6) << fixedfloat(b);
    }
    

    or

    class fixedfloat
    {
    public:
        fixedfloat(float x) : x(x) {}
        float value() const { return x; }
    
    private:
        float x;
    };
    
    ostream &operator<<(ostream &out, const fixedfloat &f)
    {
        ostringstream ss;
        ss << fixed << setprecision(out.precision()) << f.value();
        string str = ss.str();
        out << str.substr(0, str.find_last_not_of('0') + 1);
        return out;
    }
    
    int main()
    {
        float b = 0.1f;
    
        cout << setprecision(6) << fixedfloat(b);
    }
    

提交回复
热议问题