Question

I am looking for a possibility within C/C++ to print a float (or double) f, say f = 1.234e-15, such that it is printed as

  • f = 1.234*10^-15, or, even better, as
  • f = 1.234*10^{-15}

Can anyone help me? Maybe there is a way to get the exponent "-15" and mantissa "1.234" in base 10. I found the question how can I extract the mantissa of a double, but unfortunately that did not really help, since it only gets the mantissa in base 2.

Was it helpful?

Solution

You can print to a string using the output string stream, and then replace "e" with "*10^".

ostringstream ss;
ss << scientific << 123456789.87654321;
string s = ss.str();
s.replace(s.find("e"), 1, "*10^");
cout << s << endl;

This snippet produces

1.234568*10^+08

OTHER TIPS

Why not use string parsing? scan the string and replace e with 10^.

#include <cmath>
#include <iostream>

using namespace std;

template <typename F>
F round_away_from_zero (F x)
{
  return x < 0 ? floor(x) : ceil(x);
}

template <class O, typename F>
O &print_float (O &out, F f) {
    signed ex = round_away_from_zero(log10(f)); // exponent
    F mant = f / pow(10, ex);                   // mantissa
    out << mant << "*10^" << ex;
}

int main () {
    double f = 1.234e-15;
    print_float(cout, f) << endl; // prints 1.234*10^-15
    return 0;
}

While waiting for your solutions I came up with the following idea:

Use sprintf() to print the float or double to an array of char. Parse this to get the exponent and mantissa. Code looks now the following way:

void printDoubleToChar(double d, char* c){
    char valAsChar[256];

    sprintf(valAsChar, "%.12e", d);

    int expStart = 0, expWidth = 0;
    for(int i=0; i<sizeof(valAsChar); i++){
        if(valAsChar[i] == 'e'){
            expStart = i+1;
            break;
        }
    }
    for(int i=expStart; i<sizeof(valAsChar); i++){
        if(valAsChar[i] == '\0'){
            expWidth = i - expStart;
            break;
        }
    }

    char chValExp[32];
    memcpy(chValExp, &valAsChar[expStart], expWidth+1);

    char chValMan[128];
    memcpy(chValMan, valAsChar, expStart-1);
    chValMan[expStart-1] = '\0';

    sprintf(c, "%s*10^{%s}", chValMan, chValExp);
}

int main(){
    double myNewDbl = 3.95743e-5;
    char chDbl[256];
    printDoubleToChar(myNewDbl, chDbl);
    printf("\nchDbl: %s\n", chDbl); // output: chDbl: 3.957430000000*10^{-05}
}

But honestly, I prefer the much simpler solution by dasblinkenlight :)

Thank you all for your help!

Alex

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top