12

I would like to turn a number into a string using a comma as a thousands separator. Something like:

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

but with the effect

str = '120,501,231.21' 

If the built-in fprintf/sprintf can't do it, I imagine cool solution could be made using regular expressions, perhaps by calling Java (which I assume has some locale-based formatter), or with a basic string-insertion operation. However, I'm not an expert in either Matlab regexp's or calling Java from Matlab.

Related question: How can I print a float with thousands separators in Python?

Is there any established way to do this in Matlab?

Community
  • 1
  • 1
nibot
  • 14,428
  • 8
  • 54
  • 58
  • That works but is a bit cumbersome. I'm sure there are other ways that would be interesting/useful. – nibot Nov 22 '12 at 12:42
  • @NasserM.Abbasi: Nice find - but what a complicated approach if there are simple regular expressions instead :) – Jonas Nov 22 '12 at 13:45

2 Answers2

14

One way to format numbers with thousands separators is to call the Java locale-aware formatter. The "formatting numbers" article at the "Undocumented Matlab" blog explains how to do this:

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

str =

1,234,567.89     

where the char(…) converts the Java string to a Matlab string.

voilà!

nibot
  • 14,428
  • 8
  • 54
  • 58
8

Here's the solution using regular expressions:

%# 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
Jonas
  • 74,690
  • 10
  • 137
  • 177
  • 1
    Nope, still won't work for `120501231.890123`. I took the liberty of fixing that for you. – Eitan T Nov 22 '12 at 15:21
  • 1
    @EitanT: btw: I fixed the parenthesis typo, and added some explanation of the regular expression. Nice teamwork :) – Jonas Nov 22 '12 at 15:41