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!

Answers (1)

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 Comments

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!
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'.
All right, thank you very much!
My pleasure!
The sincerest expression of thanks here on MATLAB Answers is to Accept the Answer that most closely solves your problem.

Sign in to comment.

Asked:

on 10 Nov 2015

Commented:

on 11 Nov 2015

Community Treasure Hunt

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

Start Hunting!