Reputation: 7121
I want to print only one digit after the decimal dot.
So I write:
double number1 = -0.049453;
double number2 = -0.05000;
cout.setf(ios::fixed,ios::floatfield);
cout.precision(1);
cout << number1 << endl;
cout << number2 << endl;
My output is:
-0.0
-0.1
I want that the first line will be 0.0
(cause -0.0
is 0.0
). How should I change my code that in a case of -0.0
, it will print 0.0
?
And about the second line, why doesn't it print 0.0
(or -0.0
)?
Any help appreciated!
Upvotes: 3
Views: 3217
Reputation: 45725
To print floating point numbers, they are rounded up if they are greater or equal to the "middle" of two possible outputs, so -0.05
becomes -0.0
intentionally.
Negative zero is the result if a negative number is rounded up to zero, also intentionally. The internal floating point format (IEEE 754) distinguishes between negative and positive zero (see this link), and it seems like C++ output streams stick to this behavior.
You can overcome both problems by separating printing the sign and the absolute value of the floating point number.
cout << (number <= -.05 ? "-" : "") << abs(number);
Explanation of the comparison: For numbers equal to or smaller than -0.05
, rounding abs(number)
(which is then >= 0.05
) will be non-zero, so only then you want the sign to appear.
Note that the threshold value in this comparison depends on the output format you chose. So you should keep this printing method as local as possible in your code, where you know the exact format you want to print floating pointers.
Note: float
and double
behave exactly the same regarding these points.
Upvotes: 2