fprintf %E Leading zero
11 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(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 =
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.
0 个评论
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.
0 个评论
Matt Fig
2012-10-24
Here is another:
F = @(x)regexprep(sprintf('%13.6E\n',x*10),'(\d)(\.)(.*)','0$2$1$3')
0 个评论
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Annotations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!