【问题标题】:How to print an integer with a thousands separator in Matlab?如何在 Matlab 中打印带有千位分隔符的整数?
【发布时间】:2012-11-22 12:24:56
【问题描述】:

我想使用逗号作为千位分隔符将数字转换为字符串。比如:

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

但有效果

str = '120,501,231.21' 

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

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

Matlab 中是否有任何既定方法可以做到这一点?

【问题讨论】:

  • 这可行,但有点麻烦。我敢肯定还有其他有趣/有用的方法。
  • @NasserM.Abbasi:很好的发现 - 但是如果有简单的正则表达式,那是多么复杂的方法 :)

标签: regex matlab


【解决方案1】:

使用千位分隔符格式化数字的一种方法是调用 Java 区域设置感知格式化程序。 “Undocumented Matlab”博客中的“formatting numbers”文章解释了如何做到这一点:

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

str =

1,234,567.89     

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

瞧!

【讨论】:

  • +1:非常好。不过,也许值得注意的是,这在 Octave 中不起作用。
  • 在多语言系统上怎么样?我想使用 EN 格式。有什么办法可以选择吗?
【解决方案2】:

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

%# 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

【讨论】:

  • 不,对于120501231.890123 仍然不起作用。我冒昧地为你解决了这个问题。
  • @EitanT:顺便说一句:我修正了括号错字,并添加了一些正则表达式的解释。很好的团队合作:)
猜你喜欢
  • 1970-01-01
  • 2013-07-06
  • 1970-01-01
  • 2012-10-16
  • 2023-03-20
  • 2018-11-13
  • 1970-01-01
  • 2014-11-18
  • 1970-01-01
相关资源
最近更新 更多