fprintf %E Leading zero

20 views (last 30 days)
Peter
Peter on 24 Oct 2012
Hi there,
I am saving a text file using the fprintf command. I have specified the following format string: % 13.6E and the following number is printed: 2.166250E+02.
Can anyone suggest an easy change to the format string such that the number is printed with a leading zero and the exponential increases by one? I.E the number becomes 0.2166250E+03.
Many thanks for the help.

Answers (4)

Sven
Sven on 24 Oct 2012
Edited: Sven on 24 Oct 2012
Interesting question Peter...
Here's a solution I found, which pretty much involves brute force shifting of characters around the ".", and incrementing characters after the "E"
sprintfPrettyE = @(num)regexprep(sprintf('%13.6E', num), '(\d)\.(\d+)E((+|-)\d+)', '0.$1$2E${sprintf(''%02d'',str2num($3)+1)}')
>> sprintfPrettyE(2.166250E+02)
ans =
0.2166250E03
This is pretty close to what you're looking for... You'll notice that the +/- sign after the "E" is gone though... It will only show up when it is a "-" sign. Do you need it in for the plus sign too?
If so, you can wrap the whole thing in another regexprep to add a "+" sign:
sprintfPrettyE = @(num)regexprep( regexprep(sprintf('%13.6E', num), '(\d)\.(\d+)E((+|-)\d+)', '0.$1$2E${sprintf(''%02d'',str2num($3)+1)}'), 'E(\d)', 'E+$1')
>> sprintfPrettyE(2.166250E+02)
ans =
0.2166250E+03
Thanks, Sven.

Star Strider
Star Strider on 24 Oct 2012
This came up in another question, Normalizing the E descriptor a few months ago. I sketched out a solution for it.

Matt Fig
Matt Fig on 24 Oct 2012
Here is another:
F = @(x)regexprep(sprintf('%13.6E\n',x*10),'(\d)(\.)(.*)','0$2$1$3')

Dr. Seis
Dr. Seis on 24 Oct 2012
Here is a potentially lame way of doing it:
temp_num = 216.6250;
temp_str = sprintf('%13.11e',temp_num*10);
temp_str = sprintf('0.%s%s',temp_str(1:end~=2))
temp_str =
0.216625000000e+03

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!