Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ setprecision(2) printing one decimal?

Tags:

c++

I'm trying to do some simple output in formatted text. Setprecision is not printing my variables out to two decimal places.

For example if firstItemPrice = 2.20, the output is 2.2 instead of 2.20

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{

    string firstitem = "";
    string seconditem = "";
    double firstItemNum;    
    double firstItemPrice = 0.00;
    double secondItemNum;
    double secondItemPrice = 0.00;

    //first item
    cout << "Enter the name of Item 1: ";
    getline(cin, firstitem);
    cout << "Enter the number of " << firstitem << "s and the price of each: ";
    cin >> firstItemNum >> firstItemPrice;
    cin.ignore();

    //second item
    cout << "Enter the name of Item 2: ";
    getline(cin, seconditem);
    cout << "Enter the number of " << seconditem << "s and the price of each: ";
    cin >> secondItemNum >> secondItemPrice;


    cout << left << setw(20) << "Item"  << setw(10) << "Count"
    << setw(10) << "Price" << left << "\n";

    cout << setw(20) << "====" << setw(10) << "====" << setw(10)
    << "====" << left << "\n";

    cout << setw(20) << firstitem << setw(10)
    << firstItemNum << setw(10) << setprecision(2)
    << firstItemPrice << "\n";

    cout << setw(20) << seconditem << setw(10) << secondItemNum
    << setprecision(2) << secondItemPrice << left << "\n";


    return 0;
}
like image 218
lloyd Avatar asked May 17 '13 22:05

lloyd


1 Answers

You need a fixed in there to do that.

cout << fixed;

Set it back using:

cout.unsetf(ios_base::floatfield);

In your case, changing the last bit of your program like this example should do it:

cout << setw(20) << firstitem << setw(10)
<< firstItemNum << setw(10) << fixed << setprecision(2)
<< firstItemPrice << "\n";

cout.unsetf(ios_base::floatfield);

cout << setw(20) << seconditem << setw(10) << secondItemNum
<< fixed << setprecision(2) << secondItemPrice << left << "\n";

Editorial aside: Don't use floating point numbers to represent currency values.

like image 191
Carl Norum Avatar answered Sep 21 '22 13:09

Carl Norum