Clear Filters
Clear Filters

Fprintf Numerical Specifiers for fixed number of integers ?

14 views (last 30 days)
Hi All,
Quick question: What specifiers can use I to set the total number of integers that display when writing an output? I need to have a total of 7 characters, and my problem is that the number of characters before and after the decimal varies. I don't care about the number integers after the decimal as long as the total number of characters does not exceed 8.
SO....
123.4567890 >> 123.4567
1.234567890 >> 1.234567
-1234.567890 >> -1234.56
1234567.890 >> 1234567.

Answers (2)

Walter Roberson
Walter Roberson on 22 Dec 2012
Edited: Image Analyst on 23 Dec 2012
There is no direct method, but you can use
T = sprintf('%.6f', TheNumber);
fprintf('%s', T(1:8));

Image Analyst
Image Analyst on 22 Dec 2012
Edited: Image Analyst on 22 Dec 2012
It seems dangerous to limit it to 8 digits for when you have more than 8 digits to the left of the decimal point, but you can do this:
m = [...
123.4567890 %>> 123.4567
1.234567890 %>> 1.234567
-1234.567890 %>> -1234.56
1234567.890 %>> 1234567.
123456789123] % DANGER - WILL CHOP OFF DIGITS!
% Convert numerical array to 2D character array.
s = num2str(m)
for row = 1 : size(s, 1)
% Get just one row of s, trimming off blanks.
oneRow = strtrim(s(row, :));
% Get length.
lastIndex = min(length(oneRow), 8);
% Assign up to 8 characters max.
s_8_columns_Only{row} = oneRow(1:lastIndex);
end
% Print out to command window:
celldisp(s_8_columns_Only)
  2 Comments
Walter Roberson
Walter Roberson on 22 Dec 2012
The %.6f format I used is a bit of a trick: it handles the case of all of the useful information being to the right of the decimal, following '0' and '.', and it will 0 pad to the right to make 6 characters after the decimal, for a total of 8 minimum. Then since the length is always at least 8, I do not need to test the length and can instead just take the first 8 characters of the output. Simplifies the code.
Image Analyst
Image Analyst on 23 Dec 2012
Yes, clever and simpler. Though both our methods limit output to 8 characters and he should be aware of that, though maybe he doesn't need to if he knows for a fact that there will be no number greater than 99999999.9

Sign in to comment.

Categories

Find more on Numeric Types 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!