Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top