如何在Matlab中打印带千位分隔符的整数?

时间:2012-11-22 12:24:56

标签: regex matlab

我想使用逗号作为千位分隔符将数字转换为字符串。类似的东西:

x = 120501231.21;
str = sprintf('%0.0f', x);

但效果

str = '120,501,231.21' 

如果内置fprintf / sprintf无法做到这一点,我想可以使用正则表达式来制作很酷的解决方案,可能是通过调用Java(我假设它有一些基于语言环境的格式化程序) ),或基本的字符串插入操作。但是,我不是Matlab regexp的专家,也不是Matlab的Java专家。

相关问题: How can I print a float with thousands separators in Python

Matlab 中有没有确定的方法?

2 个答案:

答案 0 :(得分:13)

使用千位分隔符格式化数字的一种方法是调用支持Java语言环境的格式化程序。 “Undocumented Matlab”博客中的“formatting numbers”文章介绍了如何执行此操作:

>> nf = java.text.DecimalFormat;
>> str = char(nf.format(1234567.890123))

str =

1,234,567.89     

其中char(…)将Java字符串转换为Matlab字符串。

瞧!

答案 1 :(得分:8)

以下是使用正则表达式的解决方案:

%# 1. create your formated string 
x = 12345678;
str = sprintf('%.4f',x)

str =
12345678.0000

%# 2. use regexprep to add commas
%#    flip the string to start counting from the back
%#    and make use of the fact that Matlab regexp don't overlap
%#    The three parts of the regex are
%#    (\d+\.)? - looks for any number of digits followed by a dot
%#               before starting the match (or nothing at all)
%#    (\d{3})  - a packet of three digits that we want to match
%#    (?=\S+)   - requires that theres at least one non-whitespace character
%#               after the match to avoid results like ",123.00"

str = fliplr(regexprep(fliplr(str), '(\d+\.)?(\d{3})(?=\S+)', '$1$2,'))

str =
12,345,678.0000