Click here to Skip to main content
15,891,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
float num = 10.0111
printf("%E",num);

Output: 1.001110E+001

But I want = 1.00111E+1

What I have tried:

I read many website there were written that no hands on solution is available in C library.
Posted
Updated 9-Mar-16 3:54am

1 solution

The behaviour is defined by the standard (see fprintf[^]):
Quote:
The exponent shall always contain at least two digits. If the value is zero, the exponent shall be zero.

So the only solution would be printing to a buffer using sprintf() and modifying the string afterwards.

Example:
C++
char buffer[64];
sprintf(buffer, "%E", num);
char *expPos = strchr(buffer, 'E');
int exp = atoi(expPos + 1);
sprintf(expPos + 1, "%+d", exp);
printf(buffer);


[EDIT]
A version that removes also trailing zeroes before the exponent:
C++
char buffer[64];
sprintf(buffer, "%E", num);
// Locate the exponent
char *expPos = strchr(buffer, 'E');
// Get the exponent value
int exp = atoi(expPos + 1);
// Skip trailing zeroes using pre-increment to start at the last digit.
// Afterwards expPos points to the last non-zero digit
do expPos--; while (expPos > buffer && *expPos == '0');
// Overwrite trailing zeroes and exponent with short exponent
sprintf(expPos + 1, "E%+d", exp);
printf(buffer);

[/EDIT]
 
Share this answer
 
v4
Comments
Rupam Bhaduri Pro 9-Mar-16 12:30pm    
Thank you Jochen, that worked!
But I also want to remove those zeros before 'E'
Jochen Arndt 9-Mar-16 12:52pm    
This would be more difficult. The reason is that the E format uses a default precision of 6 digits (after the decimal point) printing all of them. If you know the required precision in advance, you may set it:
sprintf(buffer, "%.5E", num);

Otherwise you have to remove trailing zeroes before the exponent by modifying the string or implement your own print function by getting the exponent with log10(num), rounding that by casting to integer, dividing the num by pow(10, exp), printing the result using the 'f' format and appending the exponent (has to be tested; I'm not sure if I'm right with this).
Example:
int exp = (int)log10(num);
printf("%fE+%d", num / pow(10.0, exp), exp);

But note that the above might result in errors (which should be small enough when the input is float / single precision and the operations are perfomed with double precision).
Rupam Bhaduri Pro 9-Mar-16 12:55pm    
Can you tell that how to get the number before 'E' then I think I can do it.
Jochen Arndt 9-Mar-16 13:07pm    
See my updated solution.
Rupam Bhaduri Pro 9-Mar-16 13:16pm    
Thank you, I just found another solution after lots of trying. Now can print exactly what I want. And your last solution is more easy than mine.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900