I am working on some c++ problem which should output 22258199.5000000 this number, I have stored the result in double datatype and when I tried to print that variable using std::cout it rounds off to 22258200.0000000, I don't know why is this happening? can anybody explain? what can I do to avoid this problem?
Asked
Active
Viewed 3,364 times
2
-
2Please **[edit]** your question with an [mcve] or [SSCCE (Short, Self Contained, Correct Example)](http://sscce.org) – NathanOliver Aug 26 '15 at 16:24
-
4You're almost certainly using a `float` type, conversion, or constant somewhere - that's the nearest single-precision value to the original. – Brett Hale Aug 26 '15 at 16:24
-
2Use cout with precision set to 15 significant figures: a good rule of thumb for a floating point double. If you're using a `float` then you're out of luck. – Bathsheba Aug 26 '15 at 16:24
-
3[What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Ivan Aksamentov - Drop Aug 26 '15 at 16:24
-
@Drop: Software developers are not [the same as] computer scientists. That article is esoteric. There is a much better one somewhere that eludes me right now. Regardless, I don't think the OP needs teaching about floating-point precision; they just need teaching about some specific conversion somewhere that they're not currently aware of. – Lightness Races in Orbit Aug 26 '15 at 16:33
-
1@LightnessRacesinOrbit was it this one? http://floating-point-gui.de/ – harold Aug 26 '15 at 16:52
-
@skyking: _"which should output 22258199.5000000"_ He doesn't want it to round to anything... – Lightness Races in Orbit Aug 26 '15 at 17:01
-
which is it `float` or `double`? it makes a difference. – Aug 26 '15 at 22:13
-
1@Bathseba thanks for the suggestion, cout.precision() did the job :) – ankit deora Aug 27 '15 at 06:40
1 Answers
4
A 32-bit float
type holds approximately 7 decimal digits, and anything beyond that will be rounded to the nearest representable value.
A 64-bit double
type holds approximately 15 decimal digits and also rounds values beyond that.
Since your value is rounding to the nearest 7-digit number, it appears you're using a float
variable somewhere. Copying a float
value to double
doesn't restore the lost digits.
This doesn't apply to your example, but it might in others - the rounding occurs in binary, not decimal, so you might end up with a value that appears to contain many more digits than I indicated above. Just know that only the first 7 or 15 are going to be accurate in decimal.

Mark Ransom
- 299,747
- 42
- 398
- 622
-
I found the problem, it was the cout stream that was causing the issue, I was using double only but it got rounded off while printing using cout. I set the precision using cout.precision(15) and it worked fine. – ankit deora Aug 27 '15 at 06:39