Question

Is there any standard way to set an ostream to print signed 0.0 uniformly without sign?

Or is this the simplest possible solution?:

double d = -0.0;
std::cout << ( d==0 ? 0.0 : d);

Edit:

I don't want to abs all, because I want to see non-0 negative numbers. I just don't want to see -0.0 (and I mean real -0, not very near ones). Can happen if you have e.g. a data set double data[100]; and mirror it: for(...) data[i]*=-1;. And a -0.0 output because of floatfield fixed and small precision would also be OK for near 0 negative numers.

Was it helpful?

Solution

You can also try to print it like this

std::cout << ( 0.0 + d);

OTHER TIPS

double d = 0;
std::cout.precision(1);
std::cout.setf(std::ios::fixed);
std::cout << d << std::endl;

This prints 0.0. The precision() call sets the (maximum) number of decimal places to display, and the std::ios::fixed manipulator tell is to use all of those decimal places even if they are zero.

EDIT: If you're seeing a minus sign, as others have pointed out, it could be due to a rounding error. Note that there is also such a thing as "negative zero" in IEEE floating point numbers. If this is the real problem then you'll have to write code to check if your number is "close to" zero and if so, print it as exactly zero.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top