C++ How can I convert a double to a string with fixed point notation so it only
ID: 3581208 • Letter: C
Question
C++ How can I convert a double to a string with fixed point notation so it only shows 2 digits after the decimal?
Here's 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. ";
else
{
for (int rows = 0; rows < NUM_ROWS; rows++)
{
SeatPrices >> price[rows];
cout << fixed << showpoint << setprecision(2);
//cout << endl << "Row " << (rows + 1) << ": ";
//cout << "$" << price[rows];
}
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(" **************************************** Theater Ticket Row: ") +
to_string(row) +
string(" Seat: ") +
to_string(seat) +
string(" Price: $") +
to_string(price[rowRequested - 1]) +
string(" **************************************** ");
}
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
Explanation / Answer
You can use below function.
boost::format("0.2%s") % {variable-name};
You can directly use it with cout.
cout << and above function.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.