views:

66

answers:

3
+4  Q: 

Formatting Output

Hello fellow www-people!

I need to output numbers in scientific notation such that there is always a "0" before the decimal point.

e.g. For the number x = 134.87546, I need to produce the output 0.134875E03 NOT 1.348755E02

Does someone know how to do this?

Thanks in Advance --Shiraz.

A: 
int exponent = floor(log10(num)) + 1;

Then just print "0.", the number without decimals, "E", then the exponent.

strager
`log()` is the natural log, in the C standard library. You want `log10()`.
Amber
Also, `ceil(log10(num))` will return `1` if the input is `10`, and `0.` concatenated with `10` is `0.10`, which when multiplied by `10^1` is `1.0` which is not equal to `10`. You really want the floor, plus 1.
Amber
@Dav, Ah, thanks. I haven't used stdmath in a long time so I just added the comment that I meant log10. Also, I didn't consider the case where powers of 10 are integers for log10, and you're right.
strager
+3  A: 
int exp = (int)log10(input)+1;
double shifted = input / pow(10.0, exp);
printf("%fE%d", shifted, exp);
Amber
A: 

You may investigate using the Boost Format library which is a general output formatting library.

Yukiko
I'm fairly certain that the fixed/scientific manipulators can't actually cause output to always have a zero before the decimal point - they're designed for standard notation which is a single digit (not a zero) before the decimal.
Amber
@Dav Ooops... I thought that was how the manipulators behaved. Removed that from my answer (and voted up your comment ;)
Yukiko