Using fprintf to output %e with one decimal point
13 ビュー (過去 30 日間)
古いコメントを表示
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
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 件のコメント
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 Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!