# Function to format number as currency?

269 views (last 30 days)
Chris on 13 Mar 2012
Commented: Walter Roberson on 1 Feb 2019
I would like to format the number as a \$xxx,xxx,xxx.xx currency, what is the easiest way to do this?

Oleg Komarov 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)

Jan 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)));

Ian on 5 Jan 2018
Very elegant answer! Note that values of N in the range from -100 to -199 are an edge case which can produce formats such as \$-,100.00
tegar palyus fiqar on 3 Feb 2018
thank you.......
Andrew Potvin on 1 Feb 2019
Integrating Ian's comment into Jan's solution.
function S = Sep1000Str(N)
S = sprintf('\$%.2f', N);
S(2,length(S)-6:-3:3) = ',';
% I.e. only the end index changed in above
S = transpose(S(S ~= char(0)));

Ned Gulley 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 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

Steven Lord on 3 Feb 2018
If you want all the numbers displayed by your code to appear as currency, use format bank.

#### 1 Comment

Walter Roberson on 1 Feb 2019
this would not give you a currency symbol, and uses North American decimal notation .