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!
답변 (1개)
Star Strider
2015년 11월 10일
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
Enrico Tapavicza
2015년 11월 10일
Star Strider
2015년 11월 10일
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
2015년 11월 11일
Star Strider
2015년 11월 11일
My pleasure!
The sincerest expression of thanks here on MATLAB Answers is to Accept the Answer that most closely solves your problem.
카테고리
도움말 센터 및 File Exchange에서 String Parsing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!