Leading zero in Matlab's scientific notation
Asked Answered
H

2

7

In Matlab, when printing using e such as fprintf('%10.5e\n', pi/100) one will get the result to be 3.14159e-02. However, what if I want the number to have a leading zero such as 0.314159e-1? How can I manage this with Matlab?

The reason I ask is that I am trying to print to a file which I need to have leading zeros. Otherwise, I would not care.

Thanks.

Huxham answered 8/5, 2013 at 23:20 Comment(0)
S
3

I don't think there is any clever way to do it:

your_number = pi;
['0.' strrep(sprintf('%10.5e',your_number*10), '.', '')]

>> ans =

0.314159e+01
Saying answered 9/5, 2013 at 1:20 Comment(0)
V
1

my solution is pretty crude but this is just to illustrate. You can do it yourself with a small function that will look for the relevant strings in the number, trim it after e, add 0. in the beginning and increse by 1 the exponent at the end, for example:

function b=fooo(a)
b=a;
k1 = strfind(a, '.');
k2 = strfind(a, 'e-');
suffix=num2str(str2num(b(k2+1:k2+3))+1);
b(k2+1:end)=[];
b(k1)=[];
b=['0.' b suffix];

where an input like

ans=fooo(sprintf('%10.5e\n', pi/100))

will yield the answer:

ans =
   0.314159e-1
Vara answered 9/5, 2013 at 1:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.