## Function to format number as currency?

on 13 Mar 2012

### Oleg Komarov (view profile)

I would like to format the number as a \$xxx,xxx,xxx.xx currency, what is the easiest way to do this?

## Products

### Oleg Komarov (view profile)

on 13 Mar 2012

Or using java:

% Formatting according to locale

```j = java.text.NumberFormat.getCurrencyInstance();
j.format(1000.3243)
```

% Different currency

```curr = java.util.Locale.US;
j = java.text.NumberFormat.getCurrencyInstance(curr);
j.format(1000.3243)
```

For a list of java.util.Locale.*: http://docs.oracle.com/javase/1.3/docs/api/java/util/Locale.html

### Jan Simon (view profile)

on 13 Mar 2012
```function S = Sep1000Str(N)
S = sprintf('\$%.2f', N);
S(2, length(S) - 6:-3:2) = ',';
S = transpose(S(S ~= char(0)));
```

Geoff

### Geoff (view profile)

on 13 Mar 2012

I like this. By far the most efficient MatLab-based answer.

Manuel

on 29 Mar 2013

### Ned Gulley (view profile)

on 13 Mar 2012

Using SPRINTF is the way to go, but getting the commas right is tricky. I turned this into a question for Cody to see what folks suggest there. Problem 495. Formatting currency numbers.

Here's my clunky MATLAB answer, but I like Oleg's Java solution better.

```function str = disp_currency(amt)
str = fliplr(sprintf('%10.2f',abs(amt)));
str = regexprep(str,' ','');
str = str(sort([1:length(str) 7:3:length(str)]));
str(7:4:length(str)) = ',';
str = ['\$' fliplr(str)];
if amt<0
str = ['(' str ')'];
end
end
```

### Geoff (view profile)

on 13 Mar 2012

Hehe, everyone's got a different function. I wrote a pretty inefficient tail-recursive solution, which might not be the "MatLab way"... Jan's seems the best that uses MatLab features, but Oleg's would be the most correct. Some locales interchange the dot and comma (and I think sprintf will follow the locale for the '%.2f' part), so everyone else's answer (including mine) is just a fun hack =)

```% eg: num2currency( 123456.789 );
function [s] = num2currency (n, idx)
if isnumeric(n)
nstr = sprintf('\$%.2f', n);
s = num2currency( nstr, length(nstr) - 5 );
elseif ~ischar(n) || nargin ~= 2
error( 'Invalid parameters' );
elseif idx < 3
s = n;
else
s = num2currency( [n(1:idx-1) ',' n(idx:end)], idx-3 );
end
end
```

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi