C ++如何将double转换为字符串,以便它只显示小数后的2位数?

时间:2016-12-15 18:03:29

标签: c++ visual-studio

我需要将票证作为函数的字符串返回。有一些双变量,当我将其转换为to_string时,它在小数点后显示6个零。我如何格式化它,因此当我将值作为字符串返回时,它只在小数点后显示2个零?

这是我的代码:

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

1 个答案:

答案 0 :(得分:2)

使用您在std::cout上的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();
}