How to change e format?

조회 수: 16 (최근 30일)
hyein Sim
hyein Sim 2021년 3월 19일
댓글: hyein Sim 2021년 3월 21일
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)
hyein Sim
hyein Sim 2021년 3월 21일
@Rik Yes!! :)

댓글을 달려면 로그인하십시오.

채택된 답변

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