How to change e format?

16 次查看(过去 30 天)
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 个评论
Rik
Rik 2021-3-19
So you just want to format the exponent with 3 digits instead of 2? (And use '%.4f' for values larger than 5e-5)

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2021-3-19
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)
[5E-005; 0.0002; 1.00; 0.0015; 0.02; 0.01; 0.003141593; 0.000314159;]
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
  1 个评论
hyein Sim
hyein Sim 2021-3-21
Thank you for kind responses 👍 I will try this and write the results.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by