-1
我需要從函數返回票證作爲字符串。有一些雙變量,當我將它轉換爲to_string時,它在小數點後顯示6個零。我怎樣才能格式化它,因此它只在小數點後面顯示2個零時,我將該值作爲字符串返回?C++如何將double轉換爲字符串,使其僅在小數點後顯示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*/
數值類型,如'double'沒有格式化。他們只是價值觀。當你將**這樣一個值轉換爲文本表示時,格式描述了你希望文本表示看起來像什麼。 –
另外,當處理貨幣/貨幣時,你應該使用兩個整數變量。一個用於整個美元,另一個用於美分。這給你一個更適合的固定點類型,因爲你不能有一分之一的分數。 – NathanOliver
我認爲這輪到百分之一的位置,但你可以調整的地方:http://stackoverflow.com/a/25429632/2642059 –