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.
A leading zero is any 0 digit that comes before the first nonzero digit in a number string in positional notation.
Scientific notation For example, 1,400,000 can be written as 1.4 x 106. In MATLAB (and other programming languages) a convenient shorthand for this is 1.4e6.
Select MATLAB > Command Window, and then choose a Numeric format option. The following table summarizes the numeric output format options. Short, fixed-decimal format with 4 digits after the decimal point.
you can use "format short g" command in the start of the code. I am a fresher in matlab but as far as i know it can help to get rid of e in the answer.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With