fprintf %E Leading zero

29 ビュー (過去 30 日間)
Peter
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
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 =
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 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 =
0.216625000000e+03

カテゴリ

Help Center および File ExchangeGraphics Object Programming についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by