Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

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

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

float a = 0.000001f;
float b = 0.1f;

cout << "a: " << a << endl;     //  1e-006 terrible, don't want sci notation.
cout << "b: " << b << endl;     //  0.1 ok.

cout << fixed << setprecision(6);
cout << "a: " << a << endl;     //  0.000001 ok.
cout << "b: " << b << endl;     //  0.100000 terrible, don't want trailing zeros.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...