35

Possible Duplicate:
How do I print a double value with full precision using cout?

float a = 175.;
   cout << a;

If I run the previous code I'll get just 175, how can I cout the number with (for example) 3 decimal places even they were zeros .. How can I print "175.000" ?!

Wolf
  • 9,679
  • 7
  • 62
  • 108
Muhammad Barrima
  • 565
  • 3
  • 6
  • 9

2 Answers2

65

You need std::fixed and std::setprecision:

 std::cout << std::fixed << std::setprecision(3) << a;

These require following header:

#include <iomanip>
Ancurio
  • 1,698
  • 1
  • 17
  • 32
Jesse Good
  • 50,901
  • 14
  • 124
  • 166
  • 12
    Ahh, iostreams... seamlessly combining the speediness of a turtle and the beauty of Andrew LLoyd-Webber. – Kerrek SB Feb 03 '13 at 21:42
  • 1
    For future reference, if you're outputting multiple values, you only need to pass the manipulators once: `float a = 2.5; float b = 3.5; std::cout << std::fixed << std::setprecision(3); std::cout << a << std::endl; std::cout << b << std::endl;` – Kyle Jul 11 '19 at 13:39
  • @MuhammadBarrima Please accept this answer if that's what you needed to show that this question is resolved. – ReinstateMonica3167040 Dec 07 '19 at 15:31
6

Try setprecision:

cout.setf(ios::fixed);
cout << setprecision(3) << a << endl;