Quantitative Analysis, Risk Management, Modelling, Algo Trading, and Big Data Analysis

Bank format of numbers in Matlab

The following Matlab function allows for displaying any double-type number using a nice bank format that includes commas separators and two digit precision (without rounding). The number $num$ is converted into a new variable of a string type.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function [str]=bankformat(num)
    num2=floor(num*1000)/1000;
    r=int32(100*(num-floor(num)));
    str = num2str(num2);
    k=find(str == '.');
    if(isempty(k))
        str=[str,'.00'];
    end
    FIN = min(length(str),find(str == '.')-1);
    for i = FIN-2:-3:2
        str(i+1:end+1) = str(i:end);
        str(i) = ',';
    end
    x=mod(r,10);
    if(x==0)
        str=[str,'0'];
    end
    k=find(str == '.');
    d=length(str)-k;
    if(d>2)
        str=str(1:end-(d-2));
    end
end

Example:

>> n=70149506.5;
>> s=bankformat(n);
>> fprintf('\nInvested capital: £\%1s\n',s)
 
Invested capital: £70,149,506.50
Contact Form Powered By : XYZScripts.com