Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print constant exponent value using printf in c

Tags:

c

I used %e format specifier. Tried %3.2e or %4.3e.

Example:
if var=0.001342, then I want to print 0.1342e-02. But prints 1.342e-03
if var=0.543124, then I want to print 54.3124e-02. But prints 5.43124e-01
if var=0.0123653, then I want to print 1.23653e-02.

That is what ever maybe the value, I just want to fix my exponent value an print the result.

like image 984
Markandeya Janaswamy Avatar asked Mar 27 '15 06:03

Markandeya Janaswamy


2 Answers

It is not possible to specify the number of digits before the decimal separator with the standard floating point format specifiers.

It is the whole point of "scientific notation" to have one (or zero) digits before the decimal point and all the info about "where is the decimal point" comes from the exponent.

If you have some fixed format (always e-2) you may produce something like:

printf("%f  e-2", x*100.0);

Edit

Or, to make it more standard scientific notation:

printf("%f * 10^-3", x*1e3);
like image 127
DrKoch Avatar answered Sep 21 '22 13:09

DrKoch


From the manual:

eE The double argument is rounded and converted in the style [-]d.ddde+-dd where there is one digit before the decimal-point character and the number of digits after it is equal to the precision; if the precision is missing, it is taken as 6; if the precision is zero, no decimal-point character appears. An E conversion uses the letter E' (rather thane') to introduce the exponent. The exponent always contains at least two digits; if the value is zero, the exponent is 00.

eE is for the scientific notation, so only one non nul digit before the decimal point.

You need to make the conversion by yourself, like:

float number = 0.01023;
float normalized = number*100;
int mantissa_int_part = normalized;
int mantissa_decimal_part = (normalized-mantissa_int_part)*10000;
printf("%02d.%04d e-2",mantissa_int_part,mantissa_decimal_part);
like image 23
Jean-Baptiste Yunès Avatar answered Sep 21 '22 13:09

Jean-Baptiste Yunès