如何在没有科学记数法或尾随零的情况下将浮点数输出到 cout

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

本文关键字:情况下 浮点数 cout 输出      更新时间:2023-10-16

在没有科学记数法或尾随零的情况下输出C++浮点数的最优雅方法是什么?

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.

我不确定"最优雅的方式",但这里有一种方法。

#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;
}

如果您需要大量此类输出,您可以创建自己的I/O操纵器。 这可以说更优雅,但实现可能类似。

如果字符串操作不会伤害你的眼睛:

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);
}

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);
}

另一个像我的例子实际上输出"200",或者"200">>"2"。

这应该适用于所有内容(因为我从字符串到我使用的 val 函数)。

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;
}
相关文章: