BlackHawkD721
BlackHawkD721

Reputation: 21

floating point values not displaying accurate number of digits c++

Having trouble giving the correct digits for my $ output.

every time i plug in for example 8 in the statement i get numbers with 3 digits Ex. 10.9 While i would like it to display $10.90

I just added the setprecision hoping that it will fix the issue, did not work

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


int main()
{
    int Ts;    // holds Ts 
    float Price, Tcost, Total;


    cout << "How many shirts you like ?" << endl;
    cin >> Ts;

    Total = 12 * Ts;

    if ( 5 < Ts && Ts < 10)
        Tcost = (Total - (.10 * Total));
        Price = (Tcost / Ts);
        cout << "he cost per shirt is $" << setprecision(4) << Price << " and the total cost is $" << Tcost << setprecision(4) << endl;




    return 0;


}

Upvotes: 2

Views: 101

Answers (2)

Arnav Borborah
Arnav Borborah

Reputation: 11789

Use a combination of std::fixed(Which will set the amount of decimals after the point to be printed as decided by setprecision(N)) and std::setprecision(2) (So that two decimals are printed), and the code should now work:

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


int main()
{
    int Ts;    // holds Ts 
    float Price, Tcost, Total;


    cout << "How many shirts you like ?" << endl;
    cin >> Ts;

    Total = 12 * Ts;

    if ( 5 < Ts && Ts < 10)
        Tcost = (Total - (.10 * Total));
        Price = (Tcost / Ts); // The indentation is weird here
                              // but I will leave it as it is
        cout << "he cost per shirt is $" << fixed << setprecision(2) << Price << " and the total cost is $" << Tcost << setprecision(2) << endl;
    return 0;


}

The output I get from this is:

How many shirts you like ?
8
he cost per shirt is $10.80 and the total cost is $86.40

Upvotes: 2

BAE HA RAM
BAE HA RAM

Reputation: 605

You have to write std::cout.setf(std::ios::showpoint); then it will work.

Upvotes: 0

Related Questions