필터 지우기
필터 지우기

Is there a format in MATLAB to display numbers such that commas are automatically inserted into the display?

조회 수: 130 (최근 30일)
I would like to display large numbers with commas separating the digits for readability purposes. For example, I would like MATLAB to display one billion as 1,000,000,000 rather than 1000000000. How can I do this?

채택된 답변

MathWorks Support Team
MathWorks Support Team 2024년 2월 26일
편집: MathWorks Support Team 2024년 2월 29일
You can enhance the readability of large numbers by formatting them with commas to separate digits using the "java.text.DecimalFormat" class. See the below code for an example of this:
function numOut = addComma(numIn)
import java.text.*
jf=java.text.DecimalFormat; % comma for thousands, three decimal places
numOut= char(jf.format(numIn)); % omit "char" if you want a string out
end
Then, calling the function will result in a comma separated number.
addComma(10000.12)
% 10,000.12

추가 답변 (2개)

Ted Shultz
Ted Shultz 2018년 6월 13일
A simple way is to add this two line function:
function numOut = addComma(numIn)
jf=java.text.DecimalFormat; % comma for thousands, three decimal places
numOut= char(jf.format(numIn)); % omit "char" if you want a string out
end
Hope that helps! --ted

Toshiaki Takeuchi
Toshiaki Takeuchi 2023년 11월 14일
Using pattern
vec = 123456789;
txt = string(vec);
pat1 = lookBehindBoundary(digitsPattern); % (?<=\d)
pat2 = asManyOfPattern(digitsPattern(3),1); % (\d{3})+
pat3 = lookAheadBoundary(pat2+lineBoundary("end")); % (?=(\d{3})+$)
pat4 = pat1+pat3; % (?<=\d)(?=(\d{3})+$)
replace(txt,pat4,",")
ans = "123,456,789"
  댓글 수: 3
Toshiaki Takeuchi
Toshiaki Takeuchi 2024년 1월 30일
How about this?
str = arrayfun(@(x) string(num2str(x)), (0:500:2000)');
str2 = [str;str + ".12345"]
str2 = 10×1 string array
"0" "500" "1000" "1500" "2000" "0.12345" "500.12345" "1000.12345" "1500.12345" "2000.12345"
pat1 = lookBehindBoundary(digitsPattern); % (?<=\d)
pat2 = asManyOfPattern(digitsPattern(3),1); % (\d{3})+
pat3 = lookAheadBoundary(pat2+lineBoundary("end")); % (?=(\d{3})+$)
pat4 = pat1+pat3; % (?<=\d)(?=(\d{3})+$)
isDecimal = contains(str2,".");
str3 = split(str2(isDecimal),".");
str2(isDecimal) = str3(:,1);
str4 = replace(str2,pat4,",");
str4(isDecimal) = str4(isDecimal) + "." + str3(:,2)
str4 = 10×1 string array
"0" "500" "1,000" "1,500" "2,000" "0.12345" "500.12345" "1,000.12345" "1,500.12345" "2,000.12345"
Stephen23
Stephen23 2024년 2월 10일
편집: Stephen23 2024년 2월 10일
That seems to work much better. Note that this
str0 = arrayfun(@(x) string(num2str(x)), (0:500:2000)');
can be replaced with the much simpler and more efficient:
str1 = string(0:500:2000).';
isequal(str0,str1)
ans = logical
1

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

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by