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

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

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

    #include 
    #include 
    #include 
    
    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.

提交回复
热议问题