Fprintf Numerical Specifiers for fixed number of integers ?

조회 수: 7 (최근 30일)
Nikolay Rodionov
Nikolay Rodionov 2012년 12월 22일
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.

답변 (2개)

Walter Roberson
Walter Roberson 2012년 12월 22일
편집: Image Analyst 2012년 12월 23일
There is no direct method, but you can use
T = sprintf('%.6f', TheNumber);
fprintf('%s', T(1:8));

Image Analyst
Image Analyst 2012년 12월 22일
편집: Image Analyst 2012년 12월 22일
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
Walter Roberson
Walter Roberson 2012년 12월 22일
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 2012년 12월 23일
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

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by