1
main()
{
   double d1 = 1234.1;
   cout << "d1 = 1234.1 --> " << d1 << endl;
   double d2 = 1234.099999;
   cout << "d2 = 1234.099999 --> " << d2 << endl;
}

Output:

d1 = 1234.1 --> 1234.1
d2 = 1234.099999 --> 1234.1

I actually want to print the exact value of d2, i.e. 1234.099999 but not getting the same.

Please suggest how can I get the exact value.

mskfisher
  • 3,291
  • 4
  • 35
  • 48
  • Did something from your code get lost? There is nothing how you get d2 in there. – murrekatt Mar 04 '11 at 07:43
  • 1
    You might want to take a look at this thread: http://stackoverflow.com/questions/4217510/how-to-cout-the-correct-number-of-decimal-places-of-a-double-value – roxrook Mar 04 '11 at 09:20

1 Answers1

7

You want cout.precision http://www.cplusplus.com/reference/iostream/ios_base/precision/

Also note that d2 is not quite 1234.099999, and d1 is not quite 1234.1

Floating point numbers introduce rounding errors, which is why they round to fewer places by default, to try to display a meaningful result.

Tim
  • 8,912
  • 3
  • 39
  • 57
  • Thanks for the reply. Actually I have the requirement of storing the value (1234.099999) in character buffer, but I'm getting (1234.1) in the buffer which is creating problem for me. How can I retrive the exact value without rounding off. – Sudhir Kumar Mar 04 '11 at 10:21
  • 1
    So you want to store it as a string instead of a double? That can be done with something like `std::string d2 = "1234.099999";`? – Tim Mar 04 '11 at 15:57