How to change e format?
15 views (last 30 days)
Show older comments
I want to change the number's format.
I written
x=[0.00005; 0.0002; 1.00; 0.0015; 0.02; 0.01;];
txt=sprintf('%.e %.4f %.2f %.4f %.2f %.2f',x);
and the result is txt
5.e-05 0.0002 1.00 0.0015 0.02 0.01
But I want to change
x=[0.00005; 0.0002; 1.00; 0.0015; 0.02; 0.01;];
to
x=[5E-005; 0.0002; 1.00; 0.0015; 0.02; 0.01;];
What can I do for this?
Plz help me... ;(
9 Comments
Rik
on 19 Mar 2021
So you just want to format the exponent with 3 digits instead of 2? (And use '%.4f' for values larger than 5e-5)
Accepted Answer
Walter Roberson
on 19 Mar 2021
Please check the output for pi/1000 . Is the rule intended to be "up to 9 decimal places" like it is for 0.000314159, which would give 0.003141592 if you used truncation and 0.003141593 if you used rounding. But perhaps the rule is non-zero plus up to 5 further (so up to 6 decimal places counting from the first non-zero), in which case pi/1000 would give 0.00314159 through rounding or truncation. But if the input value happened to be 0.003141596 and the rule is non-zero+5, then is truncation to 0.00314159 okay, or would you require rounding to 0.00314160 ? And in that case where the trailing digit is not "naturally" 0 but rounded to it, do you want to preserve the trailing 0 or get rid of it, to 0.0031416 ?
Note: I preserved the trailing semi-colon before the ] that you had in your output, in case it was meaningful.
Note: I did not attempt to detect row-vectors and use commas for those, and I did not attempt to deal with 2D arrays.
x = [0.00005; 0.0002; 1.00; 0.0015; 0.02; 0.01; pi/1000; pi/10000];
txt = format_vector(x);
disp(txt)
function txt = format_vector(vec)
txt = ['[', strjoin(arrayfun(@format_number, vec, 'uniform', 0), ' '), ']'];
end
function str = format_number(num)
%format of each number includes a trailing semi-colon
if abs(num) >= 1e-4
str = sprintf('%.9f;', num);
%Rule: 1 exactly becomes '1.00' not '1.' so preserve at least 2
%decimal places
%Rule: but otherwise trim trailing 0
str = regexprep(str, '0{1,7};$', ';');
else
%Rule: exponent must have three digits
%Rule: trailing 0 after period must be removed
%Rule: if all digits after period are 0, remove period too
%Rule: exponent character must be 'E' not 'e'
str = sprintf('%.5E;', num);
str = regexprep(str, {'0+E', '\.E'}, {'E', 'E'});
str = regexprep(str, {'(E[-+])(\d);$', '(E[-+])(\d\d);$'},{'$100$2;', '$10$2;'});
end
end
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!