Sudhir Kumar
Sudhir Kumar

Reputation: 11

How to maintain Double's precision in C++

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.

Upvotes: 1

Views: 1613

Answers (1)

Tim
Tim

Reputation: 9172

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.

Upvotes: 7

Related Questions