No BSD License  

Highlights from
tablefmt

from tablefmt by J. Cogdell
Construct a fixed column-width format for printing an arbitrary-size number using e.g. fprintf.

tablefmt(Wd,number)
function fmt = tablefmt(Wd,number)
%function fmt = tablefmt(Wd,number)
%                                                           jdc 12-Oct-02
%PURPOSE: 
%        Construct a format for printing an arbitrary number with specified 
%        field width and precision, using e.g. fprintf
%INPUT:
%            Wd - field width and precision (example: 12.3) 
%                 Note: field width 'W' must be >= 8 for  
%                       exponential formats to print correctly
%        number - numerical value for which the format is to be constructed
%OUTPUT:
%            f or e format specification as string variable
%EXAMPLE:
% number = 0.123456789012345678; W = 12; d = 3;
%for i = -3:15,
%   val=(-1)^i*number*10^i;
%   fmt=tablefmt(12.3,val); 
%   fprintf([ fmt '\n'],val);
%end
%-1.2346e-004
% 1.2346e-003
%-1.2346e-002
%       0.123
%      -1.235
%      12.346
%    -123.457
%    1234.568
%  -12345.679
%  123456.789
%-1234567.890
% 12345678.90
%-123456789.0
%  1234567890
%-12345678901
% 1.2346e+011
%-1.2346e+012
% 1.2346e+013
%-1.2346e+014

W = floor(Wd);                % extract integer field width W and  precision d
d = round((Wd-W)*100)/100;
while d>floor(d),
   d = d*10;
end
ns = '100000000000000000000';
if W<8 & round(abs(number))>=str2double(ns(1:W)),
   fprintf('Warning: Numbers whose rounded absolute value is >=%s will not fit in a %d-character wide field.\n',ns(1:W),W);
end   
n = 1+floor(log10(abs(number)));       % number of digits left of decimal point
if n>=0 & n<=W-1,                             % if number can be printed using an "W" width f format
   d = min([d max([0 W-2-n])]);                % number of digits to print to right of decimal
   fmt = sprintf('%%%d.%df',W,d);
else                                        % else use an e format
   fmt = sprintf('%%%d.%de',W,W-8);
end   

Contact us