Using fprintf to output %e with one decimal point

조회 수: 18 (최근 30일)
mat geek
mat geek 2019년 4월 22일
편집: Walter Roberson 2019년 4월 22일
How can specify the the number of digits after the decimal point when using.
yearlyProfit= TotNumBatPro *(sellperbat - TotPineCost);
fprintf('Yearly Profit: $%0.1e\n',yearlyProfit)
I need it to look like. $##.#E## , but that did not do it.

답변 (1개)

Walter Roberson
Walter Roberson 2019년 4월 22일
You cannot get two digits before the decimal place in a %e format. You also cannot skip the sign after the E. Also, for large enough numbers, you might get 3 digits of exponents. Watch out for negative numbers too.
To get ##.#E## then you are going to have to pull apart the numbers yourself.
  댓글 수: 2
mat geek
mat geek 2019년 4월 22일
The requirement is to optain the following.
$##.#E##
I know that would have done %0.1e with one decimal poin which what the paper asked but that wouldn' be as required which later on said output as $##.#E##. I started to think there is a mistake with the requirement. Or is what is the way to pull apart the number as you said?
Walter Roberson
Walter Roberson 2019년 4월 22일
편집: Walter Roberson 2019년 4월 22일
The requirement is whatever the requirement is. Silly formatting requirements are often a nuisance.
S = '$';
if x < 0
S = [S '-'];
x = -x;
end
if x == 0
out = [S '00.0E00'];
else
E = floor(log10(x));
T = floor(x ./ 10.^(E-2));
TF = mod(T,10);
TB = round((T-TF)/10);
out = sprintf('%s%2d.%dE%02d', S, TB, TF, E-1);
end
The behavior of the code is questionable for values whose absolute value is between 1E-9 (inclusive) and 10 (exclusive): for them it will produce a final 'E-#' which obeys the restriction about only two places after the 'E', but not the rule that afte the 'E' there should be only digits.
For values whose absolute value is between 0 (exclusive) and 1E-9 then it will produce a final 'E-##' which disobeys the restriction about only two digits after 'E'.
... Actually I just found a bug in leading decimal places for 9.999E-9 that I do not feel like chasing down at the moment. Okay, fixed that, but the rounding is now wrong if the 4th significant digit of the number is 5 or greater. The other problem was with numbers that would be 999.5 or more after converting to have 3 significant digits so you can break them apart to ##.# : if you use floor() then you do not round correctly, but if you use round() then 999.5 or more rounds to 1000 and then you end up with $100.00E##' with ### before the decimal point.
... getting all of the details right is a nuisance.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by