Function to format number as currency?

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

 Réponse acceptée

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

11 commentaires

Nicholas Copsey
Nicholas Copsey le 7 Avr 2020
is there a way to pass through two columns of an array into this, or not?
Walter Roberson
Walter Roberson le 7 Avr 2020
is there a way to pass through two columns of an array into this, or not?
Not. Not even if you construct a java.lang.Double array and pass that in. You would need to arrayfun over the array getting back a matrix of java strings, and then figure out how to put the java strings together in a way suitable for your purposes.
x = randn(2,3); %some data
curr = java.util.Locale.US;
j = java.text.NumberFormat.getCurrencyInstance(curr);
arrayfun(@(v) string(j.format(v)), x)
ans =
2×3 string array
"$0.14" "$0.30" "($0.93)"
"($0.29)" "$0.40" "($0.18)"
... But then what? Notice that the entries are not all the same size. Do you want to put them into fixed-width columns? Should they be left-aligned? Right-aligned? Decimal-place aligned?
Is there anyway to get the symbole for Saudi Arabia currency in this code please?
curr = java.util.Locale.US;
j = java.text.NumberFormat.getCurrencyInstance(curr);
j.format(1000.3243)
The link above is not working.
Walter Roberson
Walter Roberson le 12 Mai 2020
I found a way but it is messier than seems appropriate, so I am still looking.
j = java.text.NumberFormat.getCurrencyInstance(java.util.Locale("ar", "SA"));
j.format(1000.3243)
ans = ر.س.‏ 1,000.32
HG-NU
HG-NU le 12 Mai 2020
Great ... Thanks
Hareesh Agraharam
Hareesh Agraharam le 11 Fév 2021
Modifié(e) : Hareesh Agraharam le 11 Fév 2021
instead of depedending on java, is there any other API or way in MATLAB to get the currency format based on our OS region settings?
Walter Roberson
Walter Roberson le 11 Fév 2021
That is portable? There are ActiveX methods to query the environment on Windows, but not on Mac or Linux.
Mac and Linux use the LANG environment variable and optionally some other related variables to specialize particular facets. A lot of the time you only get LANG such as en_US and you need to search the tables of standards to find out how that corresponds to particular format rules... or you need to call operating system functions to do the work for you, which means hooking in a mex or dll.
It would not surprise me if there are Python functions available though.
Stephen23
Stephen23 le 3 Nov 2021
Modifié(e) : Stephen23 le 11 Déc 2021
"It would not surprise me if there are Python functions available though."
dpb
dpb le 10 Fév 2026 à 17:24
Modifié(e) : dpb le 10 Fév 2026 à 17:36
This got bumped back up by another comment...
... But then what? Notice that the entries are not all the same size. Do you want to put them into fixed-width columns? Should they be left-aligned? Right-aligned? Decimal-place aligned?"
Indeed. In the Java=based routine I built I augmented all to the length of the longest or an optional input length value, retaining the currency symbol as the first character in the string. This ends up right-aligning which is the same as decimal point alignment for fixed-width font. Proportional fonts without specific field kerning are a nighmare, of course, for preparing tables.

Connectez-vous pour commenter.

Plus de réponses (5)

Jan
Jan le 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 commentaires

Geoff
Geoff le 13 Mar 2012
I like this. By far the most efficient MatLab-based answer.
Manuel
Manuel le 29 Mar 2013
Indeed. Nice answer!
Ian
Ian le 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
tegar palyus fiqar le 3 Fév 2018
thank you.......
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)));

Connectez-vous pour commenter.

Stephen23
Stephen23 le 12 Mai 2020
Modifié(e) : Stephen23 le 11 Déc 2021
Just one simple Python call:
num = 98765432.1;
str = char(py.locale.currency(num, pyargs('grouping',py.True)))
str = '$98,765,432.10'
Or alternatively a simple regular expression:
str = sprintf('\x24%.2f',num); % \x24 = unicode dollar symbol
regexprep(str,'\d{1,3}(?=(\d{3})+\>)','$&,')
ans = '$98,765,432.10'
Change the currency symbol as required:
str = sprintf('\x20AC%.2f',num); % \x20AC = unicode euro symbol
regexprep(str,'\d{1,3}(?=(\d{3})+\>)','$&,')
ans = '€98,765,432.10'
Can easily be defined as a function:
fun = @(n,c) regexprep(sprintf('%s%.2f',c,n),'\d{1,3}(?=(\d{3})+\>)','$&,');
fun(1234.5,'£')
ans = '£1,234.50'
Ned Gulley
Ned Gulley le 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

2 commentaires

Nicholas Copsey
Nicholas Copsey le 4 Avr 2020
can I pass an array into this function and have it work?
No, but you can
arrayfun(@disp_currency, YourArray, 'uniform', 0)
The output would be a cell array of character vectors, the same size as the input array.

Connectez-vous pour commenter.

Steven Lord
Steven Lord le 3 Fév 2018

1 vote

If you want all the numbers displayed by your code to appear as currency, use format bank.

3 commentaires

Walter Roberson
Walter Roberson le 1 Fév 2019
this would not give you a currency symbol, and uses North American decimal notation .
i think that is my favourite answer so far! although will have to check out help! to figure out how to use it ...
dpb
dpb le 6 Jan 2022
Indeed. Plus, it applies to everything, not just the currency variable(s).
I stumbled over this thread while looking for the same need for figure labels -- and first found Yair Altman's Undocumented site that illustrates the Java solution. That works nicely with the arrayfun solution as shown by Walter that can be packaged as a little utility routine.
BUT -- in this day and age, to not have such available in a much more usable and user-friendly manner is simply not acceptable state of affairs. Particularly the table object should be able to set a format by variable even though it isn't practical at the command window globally.
As the regulars are aware, I've been fiddling with the financial spreadsheets of the local community college Foundation for past couple of years in building some tools for them while we are still in transition to a real accounting package, plus we'll need to be able to retrieve data from the historical files for a long time going forward. In doing that I use the MATLAB table to retrieve the data from the spreadsheets, manipulate it and then put it back or create new ones. At the command window when doing this I do use format bank, format short, but it has the drawback that there are often tables with other variables like IDs or the like that are integral and then they're also shown with the two decimal places. It's not fatal, but annoying.

Connectez-vous pour commenter.

Geoff
Geoff le 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

Catégories

Produits

Question posée :

le 13 Mar 2012

Modifié(e) :

dpb
le 10 Fév 2026 à 17:36

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by