Like a stream float. 1 as .1, 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 the value is really <1, and then find the leading zero and delete it. Not very elegant.

+4
source share
2 answers

I can check if the value is really <1, and then find the leading zero and delete it. Not very elegant.

Agreed, but this is what you need to do without cheating in locales to define your own version of ostream :: operator <<(float). (You do not want this to be done this way.)

 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; } 
+2
source

You can write your own manipulator . Elegance, of course, controversial. It will be more or less what you are all ready to offer.

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; } 
+1
source

Source: https://habr.com/ru/post/1338290/


All Articles