C++, scientific notation, format number

abcdef picture abcdef · Aug 20, 2011 · Viewed 36.7k times · Source

Is it possible to format string in scientific notation in the following ways:

  • set fixed places in exponent: 1
  • set fixed decimal places in mantisa: 0

    double number = 123456.789
    

So the number should be formated

  1e+5

I am not able to set 0 decimal points for mantisa:

cout.precision(0);
cout << scientific << number;

result:

1.234568e+005

Answer

Praetorian picture Praetorian · Aug 20, 2011

I can't figure out how to get a single digit in the exponent field but the following matches all your other requirements.

#include <iostream>
#include <iomanip>

int main()
{
  const double number = 123456.789;

  std::cout << std::setprecision(0) << std::scientific << number << std::endl;
}

Output:

1e+05

EDIT:
Did a quick search through the standard (N3291) and couldn't find anything that talked about the number of digits in the exponent field when using scientific notation. This might be implementation defined.