Floating-point printing so that the exponent is marked with "* 10 ^" instead of "e",

I am looking for an opportunity in C / C ++ to print a float (or double) f, say f = 1.234e-15 , so that it f = 1.234e-15 as

  • f = 1.234*10^-15 , or better yet, how
  • f = 1.234*10^{-15}

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

+4
source share
4 answers

You can print to 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 fragment produces

 1.234568*10^+08 
+8
source

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

+2
source
 #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; } 
+2
source

Waiting for your decisions, I came up with the following idea:

Use sprintf () to print a float or double into a char array. Disassemble this to get the exponent and mantissa. The code is as follows:

 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 to be honest, I prefer the much simpler dasblinkenlight solution :)

Thank you all for your help!

Alex

0
source

All Articles