fprintf format -.123456879E-02
Show older comments
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)
Star Strider
on 10 Nov 2015
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
Enrico Tapavicza
on 10 Nov 2015
Star Strider
on 10 Nov 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
on 11 Nov 2015
Star Strider
on 11 Nov 2015
My pleasure!
The sincerest expression of thanks here on MATLAB Answers is to Accept the Answer that most closely solves your problem.
Categories
Find more on String Parsing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!