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

后端 未结 3 1951
谎友^
谎友^ 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);
    }
    
    0 讨论(0)
  • 2020-12-06 13:07

    I am not sure about the "most elegant way" but here's one way.

    #include <iostream>
    #include <iomanip>
    #include <sstream>
    
    using namespace std ;
    string fix( float x, int p )
    {
        ostringstream strout ;
        strout << fixed << setprecision(p) << x ;
        string str = strout.str() ;
        size_t end = str.find_last_not_of( '0' ) + 1 ;
        return str.erase( end ) ;
    }
    
    
    int main()
    {
        float a = 0.000001f ;
        float b = 0.1f ;
    
        cout << "a: " << fix( a, 6 ) << endl;     //  0.000001 ok.
        cout << "b: " << fix( b, 6 ) << endl;     //  0.1 ok.
    
       return 0;
    }
    

    You could perhaps create your own I/O manipulator if you need to to a lot of this kind of output. That is arguably more elegant, but the implementation could be similar.

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题