Function to format number as currency?

조회 수: 256(최근 30일)
Chris
Chris 2012년 3월 13일
댓글: dpb 2022년 1월 6일
I would like to format the number as a $xxx,xxx,xxx.xx currency, what is the easiest way to do this?

채택된 답변

Oleg Komarov
Oleg Komarov 2012년 3월 13일
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)
  댓글 수: 10
Stephen23
Stephen23 2021년 11월 3일
편집: Stephen23 2021년 12월 11일
"It would not surprise me if there are Python functions available though."

댓글을 달려면 로그인하십시오.

추가 답변(5개)

Jan
Jan 2012년 3월 13일
function S = Sep1000Str(N)
S = sprintf('$%.2f', N);
S(2, length(S) - 6:-3:2) = ',';
S = transpose(S(S ~= char(0)));
  댓글 수: 5
Andrew Potvin
Andrew Potvin 2019년 2월 1일
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
Ned Gulley 2012년 3월 13일
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
Walter Roberson
Walter Roberson 2020년 4월 4일
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.

댓글을 달려면 로그인하십시오.


Steven Lord
Steven Lord 2018년 2월 3일
If you want all the numbers displayed by your code to appear as currency, use format bank.
  댓글 수: 3
dpb
dpb 2022년 1월 6일
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.

댓글을 달려면 로그인하십시오.


Stephen23
Stephen23 2020년 5월 12일
편집: Stephen23 2021년 12월 11일
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'

Geoff
Geoff 2012년 3월 13일
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

Community Treasure Hunt

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

Start Hunting!

Translated by