How to stream float .1 as .1 and not 0.1
std::ostringstream oss;
oss << std::setw(10);
oss << std::setfill(' ');
oss << std::setprecision(3);
float value = .1;
oss << value
开发者_开发百科I can check if value < 1 and then find the leading zero and remove it. Not very elegant.
I can check if value < 1 and then find the leading zero and remove it. Not very elegant.
Agreed, but that's what you have to do without mucking around in locales to define your own version of ostream::operator<<(float). (You do not want to do this mucking around.)
void float_without_leading_zero(float x, std::ostream &out) {
std::ostringstream ss;
ss.copyfmt(out);
ss.width(0);
ss << x;
std::string s = ss.str();
if (s.size() > 1 && s[0] == '0') {
s.erase(0);
}
out << s;
}
You could write your own manipulator. The elegance is of course debatable. It would more or less be what you've all ready proposed though.
Example:
struct myfloat
{
myfloat(float n) : _n(n) {}
float n() const { return _n; }
private:
float _n;
};
std::ostream &<<(std::ostream &out, myfloat mf)
{
if (mf.n() < 0f)
{
// Efficiency of this is solution is questionable :)
std::ios_base::fmtflags flags = out.flags();
std::ostringstream convert;
convert.flags(flags);
convert << mf.n();
std::string result;
convert >> result;
if (result.length() > 1)
return out << result.substr(1);
else
return out << result;
}
return out;
}
精彩评论