c++ scientifc notation

Hi,

When i multiply 1000 by 1000, i get 1e+006. This is just scientific notation for 1.000.000 . But a million is not a very big number to write in that notation. So is there a way to get round scientif notation for not really big numbers in c++?

hannes
see <iomanip>

http://www.cplusplus.com/reference/iostream/manipulators/

cout << fixed << your_number;
As a side-note this code ..

cout << fixed;

will actually set a flag inside the output stream so that every other following output will not be in scientific notation.

1
2
3
4
cout << numberOne; // scientific
cout << fixed;            // set the flag
cout << numberTwo; // not in scientific
cout << numberThree << numberFour;  // not in scientific 
Last edited on
I don't think that's true.

cout << fixed << a;
is 100% identical to
1
2
cout << fixed;
cout << a;


And I recall that both of them "reset" their state after something is printed. But I could be wrong on that 2nd part (I'm positive that the above is identical though).
It is true, the flag is set and not cleared from output. Some functions like

cout << setw(2) << variable;

are in fact only usable on that one line. However fixed and scientific are flags that do not reset and are defaulted to scientific. Another multi-line setting is setprecision(). You can run this code to prove their continuity throughout multiple prints:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <iomanip>
using namespace std;
int main () {
  // set fixed notation and precision of 2 decimal digits
  cout << fixed << setprecision(2);

  float num1 = 1000 * 1000;
  float num2 = 2000 * 1000;
  float num3 = 3000 * 1000;
  
  cout << num1 << endl;
  cout << num2 << endl;
  cout << num3 << endl;

  // set scientific notation
  cout << scientific << endl;
  cout << num1 << endl;
  cout << num2 << endl;
  cout << num3 << endl;
  return 0;
}
Last edited on
Ah well I never really fully understood this crap. So okay. =P

My usage of iostream is extremely minimal.
Thanks for the help, it works.

now, i have this:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <sstream>
#include <iostream>

using namespace std;

int main( ) {
	ostringstream stream;
	double g1 =  1000, g2 = 1000;
	stream<<fixed;
	stream<<g1*g2;
	cout<<stream.str( );
	return 0;
}


and this is the output:

1000000.000000


It also prints out the .00000 Is there a way not to show the .00000 when it is not necessary?

hannes
In my previous example I showed

cout << fixed << setprecision(2);

In setprecision(x), the x determins how many digits to show after the decimal point. To remove all digits after the decimal point:

cout << setprecision(0);
I know, but sometimes a double has five digits after then dot, sometimes 1 and sometimes 0.
So is there a way a can set the precision dynamicly, not with literal integers?

hannes
You can pass a variable to std::setprecision(), obviously.
Topic archived. No new replies allowed.