function [str] = num2nastranBDF(num)
% this function convert numbers to NASTRAN small-field format string 
% lField = length of the field 
% nSigFigs = SigFig value to give sprintf() for num->string conversion
% str = string to insert in NASTRAN BDF
global nSigFigs
if num == 0
    str = sprintf('%-8s',' 0.');
else
    % set lfield and get first approximation for nSigFigs
    lfield = 8;
    if num >=0
        nSigFigs = lfield;
    else 
        nSigFigs = lfield-1;
    end
    % convert number to string and reduce
    str = getReduceStr(num);
    while length(str) > lfield
        nSigFigs = nSigFigs-1;
        str = getReduceStr(num);    
    end
    % fill str with blank spaces to fill field 
    if length(str) < lfield
        str = [' ',str];
        while length(str) < lfield
            str = [str,' '];
        end
    end
end   
end
function str = getReduceStr(num)
global nSigFigs
% convert the number to a string
str = sprintf('%-0.*G',nSigFigs,num);
iE = regexp(str,'[E]','ONCE');
% nastran needs a decimal to recognize a number
if isempty(regexp(str,'[.]','ONCE'))
    if isempty(iE)
        str = [str '.'];
    else 
        str = [str(1:iE-1) '.' str(iE:end)];
        iE = regexp(str,'[E]','ONCE');
    end
end
% remove zeros (before comma)
str = regexprep(str,'^0+','');
% remove zeros (after comma)
if isempty(iE)
    str = regexprep(str,'0+$','');
end
% remove zeros in the exp
str = regexprep(str,'+0+','+');
str = regexprep(str,'-0-','-');
% remove E
if ~isempty(iE)
    str(iE) = [];
end
end
