what does the setprecision() function actually do?

I understand that the setprecision() function rounds off floating point numbers but why is the answer shown to different numbers of deciaml places for diferent floating point numbers when the parameter passed to setpresion() is the same.


1
2
3
4
5
6
7
8
9
10
11
12
  #include <iostream>
  # include <iomanip>
  using namespace std;

  int main(){
     double num1 = 1.07343;
     double num2 = 0.926758;

     cout << "num 1 = " << setprecision(3) << num1 << endl; //prints 1.07
     cout << "num 2 = " << setprecision(3) << num2 << endl; //prints 0.927

  }
Both of these numbers are showing 3 significant figures. If you want to change the width of the number, use setw instead.
Does that mean if there wasn't a leading zero in num2 they would both give the same output?

Thank you.
try this:
cout << setprecision(3) << fixed << 1.07343;
By default scientific notation is used. fixed changes that.
what do you mean by leading zero? Plus what do you want this to do anyways? If you want it to display 2 points after just change the three to two when working with numbers.
@dagurr (13)

leading zero : A leading zero is any 0 digit that comes before the first nonzero digit in a number string in positional notation source.

I'm not trying to accomplish anything with this code. I just wanted to understand why setprecision() behaved in different ways at different occasions
@kevinkjt2000

Yes it does show the expected answer. Can you also please explain what scientific noation is in this context?

Thanks a lot!
When cout is in scientific notation mode, which it is by default, setprecision affects the number of significant digits.
In fixed point mode, setprecision affects the number of places after the decimal.
@kevinkjt2000

Thank you very much!
Topic archived. No new replies allowed.