简体   繁体   中英

C++ How to convert a double to a string so it only displays 2 digits after the decimal?

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*/

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM