abcdef abcdef - 24 days ago 11
C++ Question

C++, scientific notation, format number

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

I'm not sure what C++ compiler you're using that's giving you 3 digits for the exponent—the C and C++ standards require a minimum of 2 digits for that, and that's what g++ does. There's no way to get only one digit using the standard C or C++ I/O functions, so you'll have to roll your own solution. Since doing a floating-point to string conversion is a very tricky problem [PDF], I'd strongly recommend not doing that and postprocessing the result instead.

Here's one way to do that:

// C version; you can rewrite this to use std::string in C++ if you want
void my_print_scientific(char *dest, size_t size, double value)
{
    // First print out using scientific notation with 0 mantissa digits
    snprintf(dest, size, "%.0e", value);

    // Find the exponent and skip the "e" and the sign
    char *exponent = strchr(dest, 'e') + 2;

    // If we have an exponent starting with 0, drop it
    if(exponent != NULL && exponent[0] == '0')
    {
        exponent[0] = exponent[1];
        exponent[1] = '\0';
    }
}
Comments