Is there a format in MATLAB to display numbers such that commas are automatically inserted into the display?
130 次查看(过去 30 天)
显示 更早的评论
MathWorks Support Team
2012-3-12
编辑: MathWorks Support Team
2024-2-29
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
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
0 个评论
更多回答(2 个)
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
0 个评论
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,",")
3 个评论
Toshiaki Takeuchi
2024-1-30
How about this?
str = arrayfun(@(x) string(num2str(x)), (0:500:2000)');
str2 = [str;str + ".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)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!