Formatting output of floating point numbers

Discussion in 'C++' started by Martin, Oct 27, 2006.

  1. Martin

    Martin Guest

    Hi.

    My question seems to be somewhat primitive, but I cannot find an
    appropriate solution. Is it possible to control the number of digits
    displayed in the exponent part of the scientific notation? I can use
    'precision()' member function or 'setprecision' manipulator to control
    the number of digits after the point:

    cout.setf(ios_base::scientific, ios_base::floatfield);
    cout.precision(8);
    cout << 643.2963 << endl;

    The result is 6.43296300e+002 with my stdlib. I want it to be printed
    with 2 digits in exponent part, i.e. 02, not 002. How to achieve that?

    Thanks in advance

    Martin
     
    Martin, Oct 27, 2006
    #1
    1. Advertising

  2. Martin wrote:
    > My question seems to be somewhat primitive, but I cannot find an
    > appropriate solution. Is it possible to control the number of digits
    > displayed in the exponent part of the scientific notation?


    There is no easy standard way. Streams will output as many digits as
    necessary and no more.

    You can always write your own conversion routine which you can base on
    stream conversion (say, to a string and then parsing that string).

    > I can use
    > 'precision()' member function or 'setprecision' manipulator to control
    > the number of digits after the point:
    >
    > cout.setf(ios_base::scientific, ios_base::floatfield);
    > cout.precision(8);
    > cout << 643.2963 << endl;
    >
    > The result is 6.43296300e+002 with my stdlib. I want it to be printed
    > with 2 digits in exponent part, i.e. 02, not 002. How to achieve that?


    By extracting the part after 'e' and shortening it.

    V
    --
    Please remove capital 'A's when replying by e-mail
    I do not respond to top-posted replies, please don't ask
     
    Victor Bazarov, Oct 28, 2006
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. H aka N
    Replies:
    15
    Views:
    15,821
    Ben Jones
    Mar 2, 2006
  2. Motaz Saad
    Replies:
    7
    Views:
    6,552
  3. Tommi =?ISO-8859-15?Q?M=E4kitalo?=

    formatting floating-point-numbers

    Tommi =?ISO-8859-15?Q?M=E4kitalo?=, Feb 16, 2004, in forum: C++
    Replies:
    4
    Views:
    702
    Dylan Nicholson
    Feb 18, 2004
  4. Saraswati lakki
    Replies:
    0
    Views:
    1,408
    Saraswati lakki
    Jan 6, 2012
  5. teeshift
    Replies:
    2
    Views:
    289
    Chris Pearl
    Dec 1, 2006
Loading...

Share This Page