This example program was created with the sole purpose of showing what setprecision and setw does. I dont understand the purpose of the third line that says "setprecision(5)". I commented the line out to see the difference but it looks the exact same. Is there no purpose?
cout << "\nSales Figures\n";
cout << "-------------\n";
cout << setprecision(5);
cout << "Day 1: " << setw(8) << day1 << endl;
cout << "Day 2: " << setw(8) << day2 << endl;
cout << "Day 3: " << setw(8) << day3 << endl;
cout << "Total: " << setw(8) << total << endl;
The setprecision() function is part of the "iomanip" library and is used when you need to output a float to a certain number of decimal places. This is good for displaying money amounts and other things that typically are shown with a set number of digits after the decimal point (even if those digits are 0).
Say you have a float called price: If you stored 10.0 in that float, C++ would not know how many decimal points to output when you print into the screen; setprecision(2) would make the output 10.00.
You can find the documentation at this link: https://cplusplus.com/reference/iomanip/setprecision/.
It includes the following code as an example of how setprecision() works.
// setprecision example
#include <iostream> // std::cout, std::fixed
#include <iomanip> // std::setprecision
int main () {
double f =3.14159;
std::cout << std::setprecision(5) << f << '\n'; // This outputs 3.1415
std::cout << std::setprecision(9) << f << '\n'; // This outputs 3.14159
std::cout << std::fixed;
std::cout << std::setprecision(5) << f << '\n'; // This outputs 3.14159
std::cout << std::setprecision(9) << f << '\n'; // This outputs 3.141590000
return 0;
}
Note that setprecision() is only applicable to data types with decimal points such as floats and doubles.
Related
While preparing for my first ever coding interview I found a question where I was requested to print a double number with an absolute or relative error of 10^(-6).
How can I do something like that with cout?
double test_var; // Holding Some value which changes according to my program.
cout << test_var << endl;
Plus, In the expected output I saw numbers like 1000.00 how can I print those .00 too?
You could have used std::setprecision.
#include <iostream>
#include <iomanip>
int main()
{
double f =3.14159;
std::cout << std::setprecision(5) << f << '\n'; //prints 3.1416
std::cout << std::setprecision(9) << f << '\n'; //prints 3.14159
std::cout << std::fixed; //Modifies the default formatting for floating-point input/output.
std::cout << std::setprecision(5) << f << '\n'; //prints 3.1416
std::cout << std::setprecision(9) << f << '\n'; //prints 3.141590000
}
so i think its complicated with those set or fixes
there is a simple way to acheive your goal
printf("%.6lf",test_var);
so %.6lf means to keep 6 demicals of the varible
I want to display my result aligned on the column by the decimal place.
I have tried to just put setw(7) and setw(6) in parts of the display but it seems to not change the output at all.
int main()
{
double x;
char more = 'y';
while(more=='y' || more=='Y')
{
cout << "\n\t\t\tInput x:";
cin >> x;
cout << "\n\n\t\t\t LibraryResult\tMyResult" << endl;
cout << setprecision(2) << fixed << "\n\t\tsin(" << x << ")\t"
<< setprecision(6) << sin(x) << "\t" << mySin(x) << endl;
cout << setprecision(2) << fixed << "\n\t\tcos(" << x << ")\t"
<< setprecision(6) << cos(x) << "\t" << myCos(x) << endl;
cout << setprecision(2) << fixed << "\n\t\texp(" << x << ")\t"
<< setprecision(6) << exp(x) << "\t" << myExp(x) << endl;
}
}
I want the resultants of the program to be aligned by decimal, so when you put in a number like 2 the decimals are all in the same column.
If you set a precision of 6, a width of 6 or 7 is simply not enough to contain the number. You have to either reduce the precision or increase the width.
Try playing around with the stream manipulators in the following snippet
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
int main()
{
const double period = 2 * 3.141592653589793;
const int steps = 20;
std::cout << std::string(44, '=') << '\n';
std::cout << std::setw(3) << "x" << std::setw(12) << "sin(x)"
<< std::setw(12) << "cos(x)" << std::setw(14) << "tan(x)" << '\n';
std::cout << std::string(44, '-') << '\n';
for(int i = 0; i <= steps; ++i)
{
double x = i * period / steps;
std::cout << std::setprecision(2) << std::fixed << x
<< std::setprecision(6) << std::setw(12) << std::sin(x)
<< std::setprecision(6) << std::setw(12) << std::cos(x)
<< std::setprecision(6)
<< std::setw(16) // <- Try to decrease it
<< std::scientific // <- Try to keep it as std::fixed
<< std::tan(x) << '\n';
}
std::cout << std::string(44, '-') << '\n';
}
You must use several manipulators (one is not enough)
You might want to try with the following combination, that right-aligns your numbers, with a fixed number of decimals.
std::cout.width(15);
std::cout << std::fixed << std::setprecision(6) << std::right << exp(x) << std::endl;
You can find information about manipulators here
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.
I am working on a C++ program with a lot of numbers that are type double (values in the millions and billions with just a couple places to the right of the decimal point). I am performing calculations on these numbers and then printing the result to text/CSV files. I noticed that in the text files, all of my numbers appear to be rounded (to six digits). So, a value of 13,169,911 is showing up as 13,169,900 in my output file.
Is this rounding only occuring on the print? In order to get the full number of digits in the variable, do I just need to specify something when I write to a file? I included a sample of my write to file code below:
void PrintPropFinance(vector<PropFinance>& PF, int NumProps, int Iterations, int ForecastLength,
string CurDeal, string ModelRunID, string ScenName, Assumptions& Ass) {
string filename;
ofstream OutFile;
ostringstream s1;
s1 << BASEPATH << "Output/" << CurDeal << "_" << ModelRunID << "_" <<
ScenName << "_PropFinance" << ".csv";
filename = s1.str();
OutFile.open(filename);
// Put in the column headers first
OutFile << "PropID" << ","
<< "Item" << ","
<< "StartDate" << ","
<< "NumOfPeriod" << ","
<< "Result" << ","
<< "Isap" << ","
<< "CurLoanBal" << ","
for (int i=1; i<=NumProps; ++i) {
// Populate the single-vector variables
OutFile << PF[i].PropID << ","
<< PF[i].Item << ","
<< PF[i].StartDate << ","
<< PF[i].NumOfPeriod << ","
<< PF[i].Result << ","
<< PF[i].Isap << ","
<< PF[i].CurLoanBal << ","
<< endl;
}
OutFile.close();
}
// Prop finance class definition
class PropFinance {
public:
string PropID;
int Item;
string StartDate;
int NumOfPeriod;
string Isap;
double CurLoanBal;
}
The problem is likely to do with the way the output stream produces the output for doubles: if 13169911 gets printed in "scientific notation", it would look like 1.31699E7. Excel will read this notation just fine, but would put zeros for the digits it does not "see", making the number look like 13,169,900.
To fix this problem, add fixed manipulator when you output your double to ensure that all digits get printed:
OutFile << PF[i].PropID << ","
<< PF[i].Item << ","
<< PF[i].StartDate << ","
<< PF[i].NumOfPeriod << ","
<< fixed << PF[i].Result << ","
<< PF[i].Isap << ","
<< fixed << PF[i].CurLoanBal << ","
<< endl;
You need to use std::setprecision to increase the precision of the stream. By default an iostream has only 6 digits of precision.
Try this:
OutFile << std::setprecision(std::numeric_limits<long double>::digits10 << PF[i].CurLoanBal;
Bear in mind that this will affect all subsequent operations on the stream. To be honest though, that's probably what you want!
As comparison between std::setprecision and std::fixed, this program:
#include <iostream>
#include <iomanip>
#include <cmath>
#include <limits>
int main()
{
const long double test_value = 13169911.7777777;
std::cout << "default precision (6): " << test_value << '\n'
<< "std::fixed: " << std::fixed << test_value << '\n'
<< "std::precision(10): " << std::defaultfloat << std::setprecision(10) << test_value << '\n'
<< "std::precision(10) & std::fixed: " << std::fixed << std::setprecision(10) << test_value << '\n'
<< "max precision: " << std::defaultfloat << std::setprecision(std::numeric_limits<long double>::digits10) << test_value << '\n'
<< "max precision & std::fixed: " << std::fixed << std::setprecision(std::numeric_limits<long double>::digits10) << test_value << '\n'
;
}
Produces this output:
default precision (6): 1.31699e+007
std::fixed: 13169911.777778
std::precision(10): 13169911.78
std::precision(10) & std::fixed: 13169911.7777777000
max precision: 13169911.7777777
max precision & std::fixed: 13169911.777777700000000
So I think you may want std::setprecision rather than std::fixed. Though I imagine that you'll only have two decimal places anyway so perhaps it doesn't matter.
Read more here: http://en.cppreference.com/w/cpp/io/manip/setprecision
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;
}