MATLAB Answers

Chris
2

Function to format number as currency?

Asked by Chris
on 13 Mar 2012
Latest activity Commented on by 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?

  0 Comments

Sign in to comment.

5 Answers

Answer by Oleg Komarov on 13 Mar 2012
 Accepted Answer

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)

  0 Comments

Sign in to comment.


Answer by 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)));

  5 Comments

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

Sign in to comment.


Answer by 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

  0 Comments

Sign in to comment.


Answer by 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

  0 Comments

Sign in to comment.


Answer by 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

this would not give you a currency symbol, and uses North American decimal notation .

Sign in to comment.