fprintf format -.123456879E-02

How can I use fprintf to print in scientific format, always starting with 0.XXXXXXE-0Y in case of a positive number, or -.XXXXXXE-0Y in the case of a negative number.
Example: a=-0.07639297; fprintf('%E',a);
This will print the number as: -7.639297E-02
However, I want to have it as: -.7639297E-01
Thanks!

Respuestas (1)

Star Strider
Star Strider el 10 de Nov. de 2015

0 votos

You have to ‘adjust’ the format a bit, but it can be done as a string:
a=-0.07639297;
expstr = @(x) [x*10.^floor(-log10(abs(x))) floor(log10(abs(x))+1)];
Result = sprintf('%.7fE%+04d', expstr(a))
Result =
-0.7639297E-001
Tweak the format in the sprintf call to your liking.

4 comentarios

Enrico Tapavicza
Enrico Tapavicza el 10 de Nov. de 2015
Thank you, this is already close to what I want, but how can I remove the zero before the point to get: -.7639297E-001 ?
Thanks!
Star Strider
Star Strider el 10 de Nov. de 2015
It’s possible, but the code looks really kludgy:
a=-0.07639297;
expstr = @(x) [x*10.^floor(-log10(abs(x))) floor(log10(abs(x))+1)];
exvct = expstr(a);
sgn = '- +';
Result = sprintf('%c.%7dE%+04d', sgn(sign(a)+2),abs(exvct(1)/10^(exvct(2)-7)),exvct(2))
Result =
-.76392970E-001
If you’re going to use this frequently, it would be best to wrap it in an external function, add a precision variable to make it robust to your needs (the ‘7’ values in this code would be the precision variables to adjust), and experiment with it to get the result you want. The format descriptor itself is a string, so you can create a separate sprintf call to create it, then pass it to the sprintf call that produces ‘Result’ here. ‘Result’ is a string variable, not numeric, so print it in your own fprintf call using '%s'.
Enrico Tapavicza
Enrico Tapavicza el 11 de Nov. de 2015
All right, thank you very much!
Star Strider
Star Strider el 11 de Nov. de 2015
My pleasure!
The sincerest expression of thanks here on MATLAB Answers is to Accept the Answer that most closely solves your problem.

Iniciar sesión para comentar.

Preguntada:

el 10 de Nov. de 2015

Comentada:

el 11 de Nov. de 2015

Community Treasure Hunt

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

Start Hunting!

Translated by