Correct use of std::cout.precision() - not printing trailing zeros

mahmood picture mahmood · Jun 27, 2013 · Viewed 23.1k times · Source

I see many questions about the precision number for floating point numbers but specifically I want to know why this code

#include <iostream>
#include <stdlib.h>
int main()
{
  int a = 5;
  int b = 10;
  std::cout.precision(4);
  std::cout << (float)a/(float)b << "\n";
  return 0;
}

shows 0.5? I expect to see 0.5000. Is it because of the original integer data types?

Answer

Nemanja Boric picture Nemanja Boric · Jun 27, 2013
#include <iostream>
#include <stdlib.h>
#include <iomanip>
int main()
{
  int a = 5;
  int b = 10;
  std::cout << std::fixed;
  std::cout << std::setprecision(4);
  std::cout << (float)a/(float)b << "\n";
  return 0;
}

You need to pass std::fixed manipulator to cout in order to show trailing zeroes.