How to change e format?
16 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
hyein Sim
el 19 de Mzo. de 2021
Comentada: hyein Sim
el 21 de Mzo. de 2021
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 comentarios
Rik
el 19 de Mzo. de 2021
So you just want to format the exponent with 3 digits instead of 2? (And use '%.4f' for values larger than 5e-5)
Respuesta aceptada
Walter Roberson
el 19 de Mzo. de 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
Más respuestas (0)
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!