fprintf %E Leading zero

조회 수: 22 (최근 30일)
Peter 2012년 10월 24일
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.

답변 (4개)

Sven 2012년 10월 24일
편집: Sven 2012년 10월 24일
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 =
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 =
Thanks, Sven.

Star Strider
Star Strider 2012년 10월 24일
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 2012년 10월 24일
Here is another:
F = @(x)regexprep(sprintf('%13.6E\n',x*10),'(\d)(\.)(.*)','0$2$1$3')

Dr. Seis
Dr. Seis 2012년 10월 24일
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 =


Help CenterFile Exchange에서 Annotations에 대해 자세히 알아보기


Community Treasure Hunt

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

Start Hunting!

Translated by