Format exponent notation: start with 0

If I print a floating point f in exponential notation, I get, say:
>> sprintf('%10.3E',f)
ans =
' 2.091E+05'
Can Matlab always make the leading digit a zero, always, so:
>> sprintf('%someMagicHere',f)
ans =
' 0.209E+06'
I want this irrespective of the exponent.
(I know you print less significant digits this way)

4 件のコメント

dpb
dpb 2021 年 4 月 29 日
Another example where C format string editing is hamstrung compared to Fortran -- there is no equivalent to the P Scale Factor Editing facility in C (and hence, not in MATLAB since it is based on the C fprintf i/o formatting library.
You'll have to manually scale the value as desired before printing.
Much would be far simpler if TMW had kept the Fortran FORMAT convention instead...
Arjan Lampe
Arjan Lampe 2021 年 4 月 29 日
Note that the two numbers are equal. I just change the notation
dpb
dpb 2021 年 4 月 29 日
Yes, that's what P multiplier does...changes the displayed scaled factor for the exponent.
dpb
dpb 2021 年 4 月 29 日
Yes, that's what P multiplier does...changes the displayed scaled factor for the exponent.

サインインしてコメントする。

回答 (1 件)

Star Strider
Star Strider 2021 年 4 月 29 日

0 投票

I am not certain what you are asking.
I wrote a little utility function for my own use a while back to do something like this —
a=-0.07639297;
expstr = @(x,n) [x(:).*10.^(-n*floor(log10(abs(x(:)))/abs(n))) n*floor(log10(abs(x(:)))/abs(n))];
Result_1 = sprintf('%+0.7fE%+04d', expstr(a,4))
Result_1 = '-763.9297000E-004'
Result_2 = sprintf('%+015.7fE%+04d', expstr(a,4))
Result_2 = '-000763.9297000E-004'
Putting a leading 0 in the format (just after the %) willl fill the numeric filed to the left of the decimal with leading zeros. See Optional Operators in the formatSpec section of the sprintf documentation.
Experiment with it to get the result you want.

2 件のコメント

Arjan Lampe
Arjan Lampe 2021 年 4 月 29 日
Ok, but then I need to know the value for the exponent ahead of printing. In principle it can work though, not as simple as I had hoped...
Star Strider
Star Strider 2021 年 4 月 29 日
It depends on what you want to do. The examples posted originally had different exponents, and my utility function allows that to change.
The format descriptor syntax is the same, regardless. That is a property of sprintf, fprintf, and others (such as compose) that share that syntax.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeSoftware Development Tools についてさらに検索

質問済み:

2021 年 4 月 29 日

コメント済み:

dpb
2021 年 4 月 29 日

Community Treasure Hunt

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

Start Hunting!

Translated by