double value;
std::ostringstream s;
s << std::fixed << std::setprecision(3) << value;
When value
wanders in the range -1.0e-14
to 1.0e-14
, s
flickers between "0.000"
and "-0.000"
.
Is there a clean way to suppress the minus sign, which only indicates irrelevant noise ten decimal places farther down?
(The less general case is cout << ...
.)
what is the best way to avoid negative zero in output? addresses superficial issues. Its answer, rounding to the right number of significant digits before passing to <<, is a lot of computation compared to "just drop the frickin' minus if all digits are zero."
Even if nothing in <iomanip>
can adjust the actual stream, we can at least not depend on the value passed to setprecision()
, like this:
const std::string& t = s.str();
return t.find_first_of("123456789") == t.npos && t[0] == '-' ?
t.substr(1) : t;
If no digits from 1..9 are found, then all digits must be 0.
If, furthermore, it starts with minus, then skip that character.