Is there a format in MATLAB to display numbers such that commas are automatically inserted into the display?
164 views (last 30 days)
Show older comments
For large numbers, it helps for reading purposes if the digits are separated by commas. For example, I would like MATLAB to display one billion as
1,000,000,000
rather than
1000000000
Accepted Answer
MathWorks Support Team
on 28 May 2021
Edited: MathWorks Support Team
on 28 May 2021
The ability to automatically format a number to display it with the commas inserted at the right places for easy reading is not available in MATLAB.
To work around this issue, the number needs to be converted to a string. Then, commas can be inserted between the string characters. The following function achieves this purpose:
function [str]=num2bank(num)
str = arrayfun(@(x) num2bankScalar(x) , num, 'UniformOutput', false)
end
function [str]=num2bankScalar(num)
num=floor(num*100)/100
str = num2str(num)
k=find(str == '.', 1)
if(isempty(k))
str=[str,'.00']
end
FIN = min(length(str),find(str == '.')-1)
for i = FIN-2:-3:2
str(i+1:end+1) = str(i:end)
str(i) = ','
end
end
1 Comment
tmozdzen
on 8 Jun 2022 at 18:03
Ugh! Sorry - not to your solution, but to Matlab not supporting this format style naturally.
More Answers (2)
Ted Shultz
on 13 Jun 2018
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
amir soheil
on 13 Dec 2015
Edited: Walter Roberson
on 13 Dec 2015
function strnumnew=addvilgole2(num)
if isnumeric(num)==1
strnum=num2str(num);
strnum2=regexprep(fliplr(strnum),' ','');
else
if ischar(num)==1
if sum(ismember(num,','))==0
strnum2=regexprep(fliplr(num),' ','');
end
end
end
if isempty(str2num(strnum2))==0
strnum3=[];
for i=1:size(strnum2,2)
iv=logical(abs(double(logical(i-fix(i/3)*3))-1));
if iv
if i~=size(strnum2,2)
strv=[strnum2(1,i) ','];
else
strv=strnum2(1,i);
end
else
strv=strnum2(1,i);
end
strnum3=[strnum3 strv];
end
strnumnew=fliplr(strnum3);
else
strnumnew=num;
end
%end function
example
addvilgole2(22222)
ans =
22,222
addvilgole2('22222')
ans =
22,222
addvilgole2('b222222')
ans =
b222222
0 Comments
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!