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

Learn moreOpportunities for recent engineering grads.

Apply Today**New to MATLAB?**

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?

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)

For a list of `java.util.Locale.*`: http://docs.oracle.com/javase/1.3/docs/api/java/util/Locale.html

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

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

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