32

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?

Nemanja Boric
  • 21,627
  • 6
  • 67
  • 91
mahmood
  • 23,197
  • 49
  • 147
  • 242

3 Answers3

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

Nemanja Boric
  • 21,627
  • 6
  • 67
  • 91
6

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.

stardust
  • 5,918
  • 1
  • 18
  • 20
  • 1
    There's a small mistake here I think. Instead of printing `1.234` or `1.2345`, it would round the last digit and print `1.235` and `1.2346`. – Natarich J Jan 20 '20 at 04:22
2

The behavior is correct. The argument specifies the maximum meaningful amount of digits to use. It is not a minimum. If only zeroes follow, they are not printed because zeroes at the end of a decimal part are not meaningful. If you want the zeroes printed, then you need to set appropriate flags:

std::cout.setf(std::ios::fixed, std::ios::floatfield);

This sets the notation to "fixed", which prints all digits.

Nikos C.
  • 50,738
  • 9
  • 71
  • 96