How To: Format Decimal Values In C++

For example:


#include <iostream>
using std::cout;
using std::endl;
using std::ios;

#include <iomanip>
using std::fixed;
using std::setw;
using std::setprecision;

int main()
{
  // do following once
  cout << fixed;

  double gallonCost = 1.539; // dollars
  double gallons = 10.501; // gallons
  cout << setprecision(1) << gallons
    << " gallons of gasoline costs $"
    << setprecision(2) << setw(10)
    << (gallonCost * gallons) << endl;

  return 0;
}

Output:

10.5 gallons of gasoline costs $     16.16