33

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,246
  • 7
  • 59
  • 101
Muhammad Barrima
  • 545
  • 2
  • 6
  • 9

2 Answers2

61

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

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

These require following header:

#include <iomanip>
Ancurio
  • 1,668
  • 1
  • 17
  • 30
Jesse Good
  • 48,564
  • 14
  • 115
  • 165
  • 10
    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
4

Try setprecision:

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