My program executes just fine, but I was wondering how to align my output so cents line up rather than dollars.
We've only started class a couple weeks ago, so we haven't gone over this yet. My professor says it's okay for now if they don't align, I guess I'm just OCD about it. Plus, I think it looks a lot cleaner.
Also, if the bill is $38.40, would that be four significant figures? Sorry, I haven't taken math in a while. In my output, I'm getting up to five significant figures for some reason. The most I have is four. How would I fix this, using setprecision?
cout << "Bill \t \t $ " << bill << endl;
cout << "Tax at 10.5% \t \t $"<<tax<< endl;
cout << "Sub-total \t \t $"<<subTotal<< endl;
cout << "Tip at 20% \t \t $"<<tip<< endl;
cout << endl;
cout << "Total Bill \t \t \t $"<<totalBill<< endl;
As you see, I've been trying it using the tab escape. As a reply suggests, I should use setw?
Edit for 9/10:
I've gotten all my dollar amounts rounded to two decimals, except for the bill, and I don't know how to fix it. Thanks for all the info you've given me, but it's too advanced for what we're doing right now, so I've just aligned things manually. I still need to add setw and then fix everything once that's there. I'm just asking about why the bill is only three digits. It's probably something super simple that's going right over my head.
// Declare variables
double bill, tax, subTotal, tip, totalBill;
// Variables
bill = 38.40;
tax = .105;
tip = .20;
// Calculate the tax
tax = bill * .105;
// Calculate sub-total of bill
subTotal = bill + tax;
// Calculate tip
tip = subTotal * .20;
// Calculate total amount of bill
totalBill = subTotal + tip;
cout << "Bill" " $ " << setprecision(4) << bill << endl;
cout << "Tax at 10.5%" " $ " << setprecision(3) << tax << endl;
cout << "Sub-total" " $ " << setprecision(4) << subTotal << endl;
cout << "Tip at 20%" " $ " << setprecision(3) << tip << endl;
cout << endl;
cout << "Total Bill" " $ " << setprecision(4) << totalBill << endl;
Edit: I "fixed" it. All is good now.
If you're printing money, I recommend you look at C++'s money I/O.
std::put_money will ensure you are international compliant and printing with correct rounding/precision.
Set the locale of std::cout for USD.
std::showbase will decide whether to print the $.
//settings for printing as USD
std::cout.imbue(std::locale("en_US.utf8"));
std::cout << std::showbase;
Use std::setw and std::left for formatting.
Here is an example of printing your data:
#include <iostream>
#include <string>
#include <iomanip>
//row data from example
struct Row{
std::string description;
float amount;
};
//function for printing a row
void Print(Row row);
int main(){
//example rows
Row a{"Bill",3840};
Row b{"Tax at 10.5%",403};
Row c{"Sub-total",4243};
Row d{"Tip at 20%",848};
Row e{"Total Bill",5091};
//settings for printing as USD
std::cout.imbue(std::locale("en_US.utf8"));
std::cout << std::showbase;
//format printing
Print(a);
Print(b);
Print(c);
Print(d);
std::cout << '\n';
Print(e);
}
void Print(Row row){
static const int COLUMN_WIDTH{14};
std::cout << std::setw(COLUMN_WIDTH) << std::left << row.description;
std::cout << " " << std::right << std::put_money(row.amount) << '\n';
}
result:
Bill $38.40
Tax at 10.5% $4.03
Sub-total $42.43
Tip at 20% $8.48
Total Bill $50.91
One possible way is to use setw.
cout<<setw(5)<<4.55<<endl;
cout<<setw(5)<<44.55<<endl;
output:
4.55
44.55
Update:
as Jonathan Leffler pointed out, the << operator resets the width, hence the code is updated to show it should be repeated.
I would do something like:
std::cout << std::setw(15) << std::left << "Bill";
std::cout << std::setw(15) << std::right << std::fixed << std::setprecision(2) << bill << std::endl;
std::cout << std::setw(15) << std::left << "Tax # 10.5%";
std::cout << std::setw(15) << std::right << std::fixed << std::setprecision(2) << tax << std::endl;
This sets the width of the output for each "column" to 15 characters so you don't have to rely on tabs. All of the the "labels" will be left justified, and all of the prices will be right justified and printed to 2 decimal places. This is a bit more robust than relying on tabs, where you don't have control as to how many characters are used. You can't do proper justification with tabs.
Related
I'm writing this code for my programming class and I got everything else to work however my output formatting isn't working out for me.
#include <iostream>
#include <iomanip>
#include <ios>
using namespace std;
int main()
{
double tip_fifteen;
double tip_twenty;
double tax;
double bill;
char dollars = '$';
float meal_cost;
cout << "Enter the meal cost: ";
cin >> meal_cost;
tip_twenty = meal_cost * .20;
tip_fifteen = meal_cost * .15;
tax = meal_cost * 0.0975;
cout << "******************************************" << endl;
//beginning outputs
int digits;
digits = meal_cost * 100 / 100;
cout << setw(10) << left << "Meal Cost " << dollars;
cout << setw(to_string(digits).length() + 3) << fixed << showpoint << setprecision(2) << meal_cost << endl;
cout << setw(10) << left << "Tax " << dollars;
cout << setw(to_string(digits).length() + 3) << fixed << showpoint << setprecision(2) << tax << endl;
cout << setw(10) << left << "Tip (15%) " << dollars;
cout << setw(to_string(digits).length() + 3) << fixed << showpoint << setprecision(2) << tip_fifteen << endl;
//tip outputs then final output statements
cout << setw(10) << left << fixed << setprecision(2) << "Tip (20%) " << dollars << tip_twenty << endl;
bill = tip_fifteen + meal_cost + tax;
cout << "Your total bill is " << fixed << setprecision(2) << dollars << bill << " after 15% gratuity." << endl << "or" << endl;
bill = tip_twenty + meal_cost + tax;
cout << "Your total bill is " << fixed << setprecision(2) << dollars << bill << " after 20% gratuity." << endl;
return 0;
I want my output to look like this
Enter the meal cost: 56
******************************************
Meal Cost $ 56.00
Tax $ 5.46
Tip (15%) $ 8.40
Tip (20%) $ 11.20
Your total bill is 69.86 after 15% gratuity.
or
Your total bill is 72.66 after 20% gratuity.
my output looks like this
Enter the meal cost: 56
******************************************
Meal Cost $56.00
Tax $5.46
Tip (15%) $8.40
Tip (20%) $11.20
Your total bill is $69.86 after 15% gratuity.
or
Your total bill is $72.66 after 20% gratuity.
I'm having a problem using setw with floats however it's not working when i try to set the same variable as an int.
I've also tried using setw(25) to see if that would work somehow unfortunately it has not
You need to use right if you want them aligned to the right, you also need to add a space " " after the dollars
cout << setw(10) << left << "Meal Cost " << dollars << " ";
cout << setw(to_string(digits).length() + 3) << fixed << right << showpoint << setprecision(2) << meal_cost << endl;
To this to all of the printed statements and you will get:
******************************************
Meal Cost $ 56.00
Tax $ 5.46
Tip (15%) $ 8.40
Tip (20%) $ 11.20
For there to be padding in the price column, setw has to be set to a large enough width.
For example:
std::cout << "$" << std::setw(10) << std::fixed
<< std::setprecision(2) << 56.0f << std::endl;
Prints:
$ 56.00
Your code sets the width to:
std::to_string(digits).length() + 3
Which is only 5 characters, just enough to fit "56.00". For additional padding on the left you should increase the setw width.
For a lab of mine we need to display the output values in a column following a statement of what the value is for.
Example of what I need.
Amount of adult tickets: 16
Amount of children tickets: 12
Revenue from ticket sales: $140.22
I am trying to use setw like
cout << "Amount of adult tickets: " << setw(15) << ticketsAdult` << endl;
cout << "Amount of children tickets: " << setw(15) < ticketsChildren << endl;
I'm assuming either setw is the wrong thing to use for this or I'm using it wrong as it usually results in something like
Amount of adult tickets: 16
Amount of children tickets: 12
What can I use to make the values to the right all align like they did in the example no matter the length of the "Amount of..." statements before each of them?
It looks like there is right and left alignment too. Other than that it looks like it's a pain to use.
C++ iomanip Alignment
Combining everything said together
#include <iostream>
#include <iomanip>
int main()
{
int ticketsAdult = 16;
int ticketsChildren = 12;
double rev =140.22;
std::cout << std::setw(35) << std::left << "Amount of adult tickets: " << ticketsAdult << '\n';
std::cout << std::setw(35) << std::left << "Amount of children tickets: " << ticketsChildren << '\n';
std::cout << std::setw(35) << std::left << "Revenue from ticket sales: " << '$' << rev << '\n';
return 0;
}
I have my program doing 90% of what I want all that is left to do is get the total by adding all my subtotals and outputting to a file. It my be something simple but I can't seem to find a way to get the total of all my subtotals added together. To be honest, even though I need to make it output into a text file I have not attempted anything yet because I was trying to figure a way to get my total. Would someone mind finding me a solution and explaining it so I get a better understanding.
//Libraries
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
int main() {
ifstream theFile("input.txt");
string name;
int units;
double price, subtotal;
cout << "\n" <<string(80, '*') << endl;
cout.width(66); cout << "Inventory Report For Jane Doe International Hardware" << endl;
cout << string(80, '*') << "\n" << endl;
cout << left << setw(20) << "ITEM";
cout << right << setw(20) << "NUMBER OF UNITS";
cout << right << setw(20) << "UNIT COST ($)";
cout << right << setw(20) << "TOTAL VALUE ($)" << endl;
cout << string(80, '-') << "\n" <<endl;
cout << fixed;
cout << setprecision(2);
while (theFile >> name >> units >> price) {
subtotal = units*price;
cout << left << setw(20) << name << right << setw(15) << units << right << setw(20) << price << right << setw(20) << subtotal <<endl;
}
cout << "\n" <<string(80, '-') << endl;
cout <<left << setw(20) << "Inventory Total ($)" << right << setw(55) << "total" <<endl;
return 0;
}
My input text file
Chisel 50 9.99 Hammer 30 15.99 Nails 2000 0.99
Bolts 200 2.99 Nuts 300 1.99 Soap 55 1.89
You need to sum up all subtotals. However, each subtotal is only accessible in its iteration, afterwards, it's lost since you reassign subtotal.
Hence, declare a variable total outside of your while loop, then add the subtotal to the total in each iteration. Thus, add the following line
subtotal = units*price;
total += subtotal;
Now you can print total later on.
I've been trying to align the following code for the last 3 hours with zero success. Could anybody fill me in about what I'm doing wrong?
My aim is to have the string literal left aligned and the variable right aligned like this:
Loan amount: $ 10000.00
Monthly Interest Rate: 0.10%
But this is what I keep geting:
Loan amount: $ 10000.00
Monthly Interest Rate: 0.10%
And this is the most recent version of what I've been trying:
cout << setw(25) << "Loan amount:" << right << "$ "<< amount << endl;
cout << setw(25) << "Monthly Interest Rate:"<< right<< rateMonthly << "%" << endl;
I would really appreciate some help.
The setw field width is defined for the next item to be output and is reset to 0 afterwards. This is why only the text is displayed on 25 chars and not the remaining output on the line.
The right and left justifier define where the fill chars are to be put in the field. This means that it applies only to the current field if it has a defined width. This is why the justification is not applied to the items following the text.
Here you to obtain the expected result:
cout <<setw(25)<< left<< "Loan amount:" << "$ "<< setw(10)<<right << amount << endl;
cout <<setw(25)<< left << "Monthly Interest Rate:"<<" "<<setw(10)<<right<< rateMonthly << " %" << endl;
If you want the $ to be next to the number, you have to make sure that the $ and the number are concatenated into a single object to output, either by puting them together in a single string, or by using monetary format.
Here's the live demo, which should output exactly what you want.
There's no way to set the precision with std::to_string(double), that's why I've created a small helper to do it.
auto to_string_precision(double amount, int precision)
{
stringstream stream;
stream << fixed << setprecision(precision) << amount;
return stream.str();
};
cout << setw(25) << left << "Loan amount:" << setw(10) << right << ("$ " + to_string_precision(amount, 2)) << endl;
cout << setw(25) << left << "Monthly Interest Rate:" << setw(10) << right << (to_string_precision(rateMonthly, 2) + "%") << endl;
Alternative, I still think this one looks better:
cout << setw(25) << left << "Loan amount:" << "$ " << amount << endl;
cout << setw(25) << left << "Monthly Interest Rate:" << rateMonthly << "%" << endl;
If you want
Loan amount: $ 10000.00
Monthly Interest Rate: 0.10%
If you don't want to bother with left and right you can use
cout << "Loan amount:" <<setw(25)<< "$ "<< amount << endl;
cout << "Monthly Interest Rate:"<< setw(19)<< rateMonthly << "%" << endl;
You can use the following
cout << setw(25) << left << "Loan amount:"<< "$ " << amount << endl;
cout << setw(28) << left << "Monthly Interest Rate:" << rateMonthly << "%" <<endl;
I'm working on a project where I need to do some math and give the user output with dollars in it, so I would like to have my console tell the user an answer like $20.15 instead of $20.153. I used the set precision function as such:
cout << setprecision(2);, but rather than have the numbers become what I want them to be, they are converted into scientific notation.
I'm outputting a lot of numbers, so having a function like setprecision would be best for me for ease of use.
How do I properly have the numbers displayed with only two decimal places and not have the console give me numbers in scientific notation?
Thanks
Nathan
EDIT:
Here is the part of my code I'm having problems with:
int main() {
cout << setprecision(2);
if (totalCostHybrid < totalCostNonHybrid) {
cout << "Hybrid car: " << endl;
cout << "Total cost: " << totalCostHybrid << endl;
cout << "Total gallons used: " << milesPerYear / hybridEffic << endl;
cout << "Total gas cost: " << gasCostHybrid << endl;
cout << "Non-hybrid car: " << endl;
cout << "Total cost: " << totalCostNonHybrid << endl;
cout << "Total gallons used: " << milesPerYear / nonHybridEffic << endl;
cout << "Total gas cost: " << gasCostNonHybrid << endl;
cout << "Hybrid is cheaper!" << endl;
}
Obviously there's more to it, but this is what I need help with.
To fix that, you should use fixed floating-point notation for cout. You can find more info here.
Try addind cout << fixed to your code, like the code below. To set the precision to 2, you can use the precision property.
cout << fixed;
cout.precision(2);
Here is the complete code:
using namespace std;
int main() {
cout << fixed;
cout.precision(2);
if (totalCostHybrid < totalCostNonHybrid) {
cout << "Hybrid car: " << endl;
cout << "Total cost: " << totalCostHybrid << endl;
cout << "Total gallons used: " << milesPerYear / hybridEffic << endl;
cout << "Total gas cost: " << gasCostHybrid << endl;
cout << "Non-hybrid car: " << endl;
cout << "Total cost: " << totalCostNonHybrid << endl;
cout << "Total gallons used: " << milesPerYear / nonHybridEffic << endl;
cout << "Total gas cost: " << gasCostNonHybrid << endl;
cout << "Hybrid is cheaper!" << endl;
}
}
Iostreams are a pain for formatting floating-point values. But why are you using floating-point to represent currency values? You should store integer pennies (or tenth-pennies) because, though you're not measuring in whole numbers of dollars, your values are actually fixed-point. And you really don't need the trouble that floating-point brings. And then you can stream the whole and "fractional" parts of your value separately (use / and %!), as integers, with a '.' in the middle.
In the meantime, try std::fixed.
Cheat and watch purists go crazy...
double time; //Only want two decimal places.
double timeCon = time * 100.0; //Pull out the two decimals I want.
int timeCut = timeCon; //Cut all decimal values.
double timeRevert = timeCut / 100.0; //Laugh.
cout << timeRevert << endl; //Watch heads explode.