Fprintf Numerical Specifiers for fixed number of integers ?

12 ビュー (過去 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 Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by