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

#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.


std::cout.precision(4); tells the maximum number of digits to use not the minimum. that means, for example, if you use

precision 4 on 1.23456 you get 1.235  
precision 5 on 1.23456 you get 1.2346

If you want to get n digits at all times you would have to use std::fixed.