-1

I need to return the ticket as a string from a function. There are some double variables and when I convert it to to_string it displays 6 zeros after the decimal. How can I format it so it only displays 2 zeros after the decimal when I return the value as a string?

Here is my code:

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

static const int NUM_ROWS = 15;
static const int NUM_SEATS = 30;
char SeatStructures[NUM_ROWS][NUM_SEATS];
double cost;
double price[NUM_ROWS];
int rowRequested,
seatNumber;

string PrintTicket(int row, int seat, double cost);

int main()
{
   ifstream SeatPrices;

   SeatPrices.open("SeatPrices.dat");
   if (!SeatPrices)
       cout << "Error opening SeatPrices data file.\n";
   else
   {
       for (int rows = 0; rows < NUM_ROWS; rows++)
   {
       SeatPrices >> price[rows];
       cout << fixed << showpoint << setprecision(2);
   }
   cout << endl << endl;
   }
   SeatPrices.close();
   cout << "In which row would you like to find seats(1 - 15)? ";
   cin >> rowRequested;
   cout << "What is your desired seat number in the row (1 - 30)? ";
   cin >> seatNumber;
   cout << PrintTicket(rowRequested, seatNumber, cost);
   return 0;
}
string PrintTicket(int row, int seat, double cost)
{
    return
   string("\n****************************************\nTheater Ticket\nRow: ") +
   to_string(row) +
   string("\tSeat: ") +
   to_string(seat) +
   string("\nPrice: $") +
   to_string(price[rowRequested - 1]) +
   string("\n****************************************\n\n");
}


/*Data from text file:
12.50
12.50
12.50
12.50
10.00
10.00
10.00
10.00
8.00
8.00
8.00
8.00
5.00
5.00
5.00*/
  • 5
    Numeric types such as `double` don't have formatting. They are simply values. When you **convert** such a value to a text representation, formatting describes what you want the text representation to look like. – Pete Becker Dec 15 '16 at 18:09
  • 2
    Also when dealing with money/currency you should use two integer variables. One for whole dollars and the other for cents. This gives you a fixed point type which is more appropriate since you can't have fractions of a cent. – NathanOliver Dec 15 '16 at 18:13
  • I think this rounds to the hundredth's position, but you can adjust the place: http://stackoverflow.com/a/25429632/2642059 – Jonathan Mee Dec 15 '16 at 18:19

1 Answers1

2

Use the same manipulators you used on std::cout on std::ostringstream:

std::string printTicket(int row, int seat, double cost)
{
    std::ostringstream os;
    os << "\n****************************************\nTheater Ticket\nRow: ";
    os << row;
    os << "\tSeat: ";
    os << seat;
    os << "\nPrice: $";
    os << std::fixed << std::setprecision(2) << cost;
    os << "\n****************************************\n\n";
    return os.str();
}
Slava
  • 43,454
  • 1
  • 47
  • 90