4

I want to globally set the ouptut precision to 2 decimal places.

I already tried to use iomanip and setprecision, however I keep getting output with 'e' in it.

This is my example code:

#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    double pay=16.78;
    double hours;
    double total;

    cout.precision(2); 

    cout << "Please enter how many hours you worked : " << endl;
    cin >> hours;

    total=hours*pay;

    cout << "You earned: " << total << endl;
}
oo_miguel
  • 2,374
  • 18
  • 30
Y3DII
  • 53
  • 1
  • 2
  • 9
  • 1
    Hello, and welcome to Stack Overflow. You might get better answers faster if you post a minimal example that exhibits the behaviour you wish to demonstrate, not your whole code. – Amadan Oct 08 '15 at 01:06
  • How to write a [mcve]. – Baum mit Augen Oct 08 '15 at 01:06
  • 1
    Possible duplicate of [How to use setprecision in C++](http://stackoverflow.com/questions/22515592/how-to-use-setprecision-in-c) – Amadan Oct 08 '15 at 01:08

3 Answers3

1

You can use something like this:

double pay = 393.2993;
std::cout << std::fixed << std::setprecision(2) << pay;

You will need to include iomanip for this to work.

#include <iomanip> 
oo_miguel
  • 2,374
  • 18
  • 30
0

If your e is a positive value, you cannot ride of them because your value is too large. This code

std::cout << std::setprecision(3) << 3e45;

//output
3e+45

If it's a negative number, your precision is not enough. Like the following code

std::cout << std::setprecision(3) << 3e-45; //

//output
3e-45

A simple way will be to use std::fixed

std::cout << std::fixed << std::setprecision(3) << 3.63e-2;

//output
0.036

But the disavantage you have with the std::fixed is it shows the zero after the last none-zero number until it reach the setprecision qunatity you set previously.

Captain Wise
  • 480
  • 3
  • 13
0

I'm not familiar with "cout.precision(2)". I would use std::setprecision(4) if I wanted my output to have 4 significant figures.

Setleaf
  • 75
  • 1
  • 7