How to properly set precision for doubles in C++ - c++

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.

Related

Having issues with mathematical calculations and setprecision() function

I seem to be having a problem with a C++ coding question. It involves mathematical arithmetic and I seem to be getting all of my outputs correct except the final one. In addition to this, the decimal point format of my answers seem to be incorrect. The answers should contain two decimal places but only two out of my four decimal point answers seem to have two decimal places. When I try to use the precision() function, the answers go into scientific notation which I do not want.
Here is the question and answer:
Here is my code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
float principal;
float interest_rate;
float times_compounded;
cout << "Hello, please enter a value for your principal: ";
cin >> principal;
cout << principal << endl;
cout << "Please enter a value for your interest rate: ";
cin >> interest_rate;
cout << interest_rate << "%" << endl;
cout << "Please enter the number of times the interest is compounded during the year: ";
cin >> times_compounded;
cout << times_compounded << endl << endl;
float interest = interest_rate * 10.197647;
float amount = principal * pow((1 + (interest_rate/times_compounded)), times_compounded);
cout << "Interest Rate: " << setw(19) << interest_rate << "%" << endl;
cout << "Times Compounded: " << setw(17) << times_compounded << endl;
cout << "Principal: " << setw(17) << "$ " << setw(7) << principal << endl;
cout << "Interest: " << setw(20) << "$ " << interest << endl;
cout << "Amount in Savings: " << setw(9) << "$ " << amount;
return 0;
}
Here are my three inputs:
1000, 4.25, 12
Any feedback would be appreciated, thank you for your time.
First, the last value is wrong because you're using the interest rate as a normal number in the formula although it's actually a percentage. So you'd need to divide it by 100:
float amount = principal * pow((1 + ((interest_rate / 100) /times_compounded)), times_compounded);
Now for the precision, you can use std::fixed in conjunction with std::setprecision to set the default floating point printing precision when using std::cout. We can use a macro to make it more readable, like:
#define FIXED_FLOAT(x, p) std::fixed<<std::setprecision(p)<<(x)
So, the full output section would look like:
cout << "Interest Rate: " << setw(19) << FIXED_FLOAT(interest_rate, 2) << "%" << endl;
cout << "Times Compounded: " << setw(17) << FIXED_FLOAT(times_compounded, 0) << endl;
cout << "Principal: " << setw(17) << "$ " << setw(7) << FIXED_FLOAT(principal, 2) << endl;
cout << "Interest: " << setw(20) << "$ " << FIXED_FLOAT(interest, 2) << endl;
cout << "Amount in Savings: " << setw(9) << "$ " << FIXED_FLOAT(amount, 2);
Also, that interest = interest_rate * 10.197647 seems fishy. Interest should just be the amount minus the principal.

Float Variable Not Working Inside Switch Statment

So this program is supposed to collect weather temperatures over 7 days using a for loop and then basically just print them back out to the user with an average temperature and the highest recorded temperature. Keep in mind, the following piece of code is a part of a much larger program. Anyway, the problem seems to be the "highest_temp1" float variable. When I run the program it produces some sort of error code instead of the highest temperature. This piece of code was tested in a separate source file and it works no problem.
switch (choice)
{
case 3:
int n;
float temperatures [7];
float lastweektemp [7] = {12.56,8.65,7.5,10,7.9,5,8};
float highest_temp1, highest_temp2;
float accumulated_temp1, accumulated_temp2;
system("CLS");
cout << "____________Weather Data____________" << endl << endl;
for (n = 0; n<7; n++)
{
cout << "What is the temperature for Day " << n+1 << " ?" << endl;
cin >> temperatures[n];
if (highest_temp1 < temperatures [n])
{
highest_temp1 = temperatures [n];
}
if (highest_temp2 < lastweektemp [n])
{
highest_temp2 = lastweektemp [n];
}
accumulated_temp1 = accumulated_temp1 + temperatures[n];
accumulated_temp2 = accumulated_temp2 + lastweektemp [n];
}
cout << endl << " Day This Week Last Week" << endl;
for (n=0; n<7; n++)
{
cout << n+1 << temperatures[n] << lastweektemp[n] << endl;
}
system("CLS");
cout << " Weather Report" << endl;
cout << " --------------" << endl << endl;
cout << "Current Week: " << endl;
cout << "-------------" << endl;
for (n=0; n<7; n++)
{
cout << "Day " << n+1 << ": " << temperatures[n] << endl;
}
cout << endl << " Average: " << accumulated_temp1 / 7 << endl;
cout << " Highest Temperature: " << highest_temp1 << endl;
cout << "Last Week: " << endl;
cout << "----------" << endl;
for (n=0; n<7; n++)
{
cout << "Day " << n+1 << ": " << lastweektemp[n] << endl;
}
cout << endl << " Average: " << accumulated_temp2 / 7 << endl;
cout << " Highest Temperature: " << highest_temp2 << endl;
system("PAUSE");
}
The highest temperature in current week is 24 but it is printing "Highest Temperature: 3.45857e+032"
This exact 'error-code' is appearing every time I run the program it doesn't change.
I am a newbie hence why I can't upload a photo.
Any help would be appreciated. I'm doing a small assignment in college. This is my first question so go easy !!
You have not assigned any value to teh variable highest_temp1 and you are comparing it with another value.
Basically you will need to assign it a value first before you compare..
highest_temp1 = 10.00
(or anything that it is supposed to contain)
You have not initialised highest_temp1 (or highest_temp1 for that matter: after that I stopped looking).
Same for accumulated_temp, which gets not initialised. can be done via
float accumulated_temp1(0);
Initialize variables before using them
float highest_temp1(-FLT_MAX); // -FLT_MAX insures results of first compare
float highest_temp2(-FLT_MAX); // Could use -1.0/0.0 of -INFINITY instead
float accumulated_temp1(0.0);
float accumulated_temp2(0.0);
For float number condition use if statements switch is not able to work in case of float number, switch only work for integer number.

Weight conversion output issue

I am currently working on a project for my C++ class and have come across an issue that I just cant seem to figure out on my own.
I am creating a weight conversion program that asks the user to input their weight (in kilograms), and outputs their weight in pounds as well as the weight they entered in kilograms (both rounded to 2 decimal places).
Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//Declarations
double kg = 0.0;
double lbs = 0.0;
double conversionRate = 2.2;
//INPUT
cout << "Enter Your Weight (kilograms): ";
cin >> kg;
//PROCESS
lbs = (kg * conversionRate);
//OUTPUT
cout << "Weight Entered: " << setprecision(2) << kg << " Kg" << endl;
cout << "Converts to: " << setprecision(2) << lbs << " lbs" << endl;
cout << "\n\n";
system("pause");
return 0;
}
This is the output I am getting for pounds:
These are the variable values when debugging:
I cant seem to figure out why it is outputting the data that is shown in the screenshot, and why its not showing decimal places as well on the kg?
Any help is appreciated!
You need to use fixed.
Either do a
cout.precision(2);
cout << "Weight Entered: " << fixed << kg << " Kg" << endl;
cout << "Converts to: " << fixed << lbs << " lbs" << endl;
or more like you did
cout << "Converts to: " << fixed << setprecision(2) << lbs << " lbs" << endl;
This outputs to:
Weight Entered: 63.5028
There is a linked case here linked to this case
Cheers
Stian
You want to do
cout << fixed << showpoint << setprecision(2) << lbs << " lbs" << endl;

Program won't Print a string array C++

I have been working on this program for awhile, but it refuses to cooperate on this last little stretch. The point of the program is to sift a data file into three arrays, sort the arrays, then print them out into a table. The problem I'm having appears to be with the table. The program is divided into four functions, and when I attempt to debug, it won't show the productName array in the function.
The malfunctioning segment of code looks like this:
void printReport (string productName[], int numberinStock[], float price[], int number_of_products)
{
float totalPrice;
cout << setw(18) << " " << "Friendly Grocer Store Inventory" << setw(17) << " " << endl;
cout << setw(18) << "Inventory Item" << setw(16) << "Number in Stock" << setw(16) << "Unit Price" << setw(16) << "Total Sales" << endl;
for (int count=0; count <number_of_products-1; count++)
{
cout << setw(18) << productName[count] << setw(16) << numberinStock[count] << setw(16) << std::setprecision(2) << price[count] << setw(16) << std::fixed << std::setprecision(2) << price[count]*numberinStock[count] << endl;
}
cout << "Total Price: " << totalPrice;
}
It will print everything else, but not the productName.
Some debugging statements outside of the for loop like cout << productName[1] will print out the proper productName but it's completely blank on the actual report.
After some debugging it seems like after printing the productName in the for loop every item after that overwrites the product name.
For example just leaving cout << setw(18) << productName[count] << setw(16) << numberinStock[count] << endl;
will produce
" 3s"
" 10h"
" 2a"
The product names there are Mangoes, Sandwich, and pizza.
I'm at a loss. Where did I mess up?
You might have screwed up passing the data into the function. If you set up test arrays in the function it should be printing correctly.
To pass arrays in C++ use the arrayname.
eg
int main ()
{
string productName[] = {"mango"};
...
printReport(productName, numofProduct);
return 0;
}

C++ currency output

I am taking a C++ course right now and have completed my final assignment. However there is one thing that is bugging me:
Though I have the correct outputs for the testing on a particular output, the basepay should be 133.20 and it is displaying as 133.2. Is there a way to have this display the extra 0 rather than leaving it off?
Anyone know if it's possible and how to do it? Thank you in advance
My code is below:
cout<< "Base Pay .................. = " << basepay << endl;
cout<< "Hours in Overtime ......... = " << overtime_hours << endl;
cout<< "Overtime Pay Amount........ = " << overtime_extra << endl;
cout<< "Total Pay ................. = " << iIndividualSalary << endl;
cout<< endl;
cout<< "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" <<endl;
cout<< "%%%% EMPLOYEE SUMMARY DATA%%%%%%%%%%%%%%%%%%%%%%%" <<endl;
cout<< "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" <<endl;
cout<< "%%%% Total Employee Salaries ..... = " << iTotal_salaries <<endl;
cout<< "%%%% Total Employee Hours ........ = " << iTotal_hours <<endl;
cout<< "%%%% Total Overtime Hours......... = " << iTotal_OvertimeHours <<endl;
cout<< "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" << endl;
cout<< "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" << endl;
If you want to do it in a C++ way, and you can compile with C++11 flags, you can use the standard library:
// Note: the value in cents!
const int basepay = 10000;
// Create a stream and imbue it with the local configuration.
std::stringstream ss;
ss.imbue(std::locale(""));
// The stream contains $100.00 (assuming a en_US locale config)
ss << std::showbase << std::put_money(basepay);
Example here.
What advantages have this approach?
It uses the local configuration, so the output will be coherent in any machine, even for the decimal separator, thousand separator, money symbol and decimal precission (if needed).
All the format effort is already done by the std library, less work to do!
use cout.precision to set precision, and fixed to toggle fixed-point mode:
cout.precision(2);
cout<< "Base Pay .................. = " << fixed << basepay << endl;
Yes, this is possible to do using stream manipulators. For example, set output to fixed floating-point notation, define precision (2 in your case) and define the fill character to '0':
#include <iostream>
#include <iomanip>
int main()
{
double px = 133.20;
std::cout << "Price: "
<< std::fixed << std::setprecision(2) << std::setfill('0')
<< px << std::endl;
}
In case you prefer a C-style formatting, here is an example of using printf() to achieve the same:
#include <cstdio>
int main()
{
double px = 133.20;
std::printf("Price: %.02f\n", px);
}
Hope it helps. Good Luck!
Check this out:
int main()
{
double a = 133.2;
cout << fixed << setprecision(2) << a << endl;
}
Output
133.20
You can change the cout properties:
cout.setf(ios::fixed);
cout.precision(2);`
now cout << 133.2; will print 133.20
You need to take a look at precision and fixed.
#include <iostream>
int main()
{
double f = 133.20;
// default
std::cout << f << std::endl;
// precision and fixed-point specified
std::cout.precision(2);
std::cout << std::fixed << f << std::endl;
return 0;
}