Using fprintf to output %e with one decimal point
7 views (last 30 days)
Show older comments
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.
Answers (1)
Walter Roberson
on 22 Apr 2019
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 Comments
Walter Roberson
on 22 Apr 2019
Edited: Walter Roberson
on 22 Apr 2019
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.
See Also
Categories
Find more on Logical 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!