proglove
proglove

Reputation: 15

Printing float and double values using cout in C++

For the following code:

#include <iostream>
using namespace std;
class Hall
{
 public:
 double cost;
};
int main()
{
 Hall hall;
 hall.cost=10000.50;
 cout<<hall.cost;
 return 0;
}

Why does this code output 10000.5 and not 10000.50, can someone explain the logic behind this?

Upvotes: 0

Views: 1529

Answers (3)

19UV
19UV

Reputation: 111

By default, C++ does not display trailing zeros, however the standard library <iomanip> can be used along with std::fixed from <iostream>. Here is an example:

#include <iostream>
#include <iomanip>
int main() {
  double myVar = 123.4;
  std::cout << std::fixed << std::setprecision(2); // 2 trailing digits
  std::cout << myVar << std::endl;
  return 0;
}

Upvotes: 1

HolyBlackCat
HolyBlackCat

Reputation: 96941

double (and floating-point variables in general) don't store a specific spelling of the number (base-10 or otherwise). That would be way too inefficient, and the ability to store meaningless zeroes would waste memory.

Instead, the numbers are encoded in a certain binary format. Printing them reproduces the base-10 spelling from binary.

Upvotes: 1

eerorika
eerorika

Reputation: 238461

can someone explain the logic behind this?

The default behaviour is not show any trailing zeroes.

Upvotes: 2

Related Questions