MATLAB Answers


Function to format number as currency?

Asked by Chris
on 13 Mar 2012

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


Log in to comment.

4 Answers

Answer by Oleg Komarov on 13 Mar 2012
 Accepted Answer

Or using java:

% Formatting according to locale

j = java.text.NumberFormat.getCurrencyInstance();

% Different currency

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

For a list of java.util.Locale.*:


Log in to comment.

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


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

Indeed. Nice answer!

Log 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 ')'];


Log 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;
        s = num2currency( [n(1:idx-1) ',' n(idx:end)], idx-3 );


Log in to comment.

Discover MakerZone

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

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!