From: Erich on
"Bruno Luong" <b.luong(a)fogale.fr> wrote in message <fug7a5$l97$1(a)fred.mathworks.com>...
> Sorry, here is a BUG fixed version:
>
> Bruno
>
> %%%%%%%%%%%%%%%%%%%%%
>
> function str=num2fixedlengthstr(num, maxlength, roundingflag)
> % function str=num2fixedlengthstr(num); OR
> % str=num2fixedlengthstr(..., maxlength, roundingflag);
> %
> % Convert double NUM to decimal string having MAXLENGTH [12]
> as maximum
> % length. Smart conversion with accurate result despite
> length constraint.
> %
> % ROUNDINGFLAG: 0 or [1]
> % 0: truncate fracional part (quicker)
> % 1: rounding fracional part (more accurate).
> %
> if nargin<2
> maxlength=12;
> end
>
> if nargin<3
> roundingflag=1; % rounding by default
> end
>
> if num>=0
> fracNDigits=maxlength;
> else
> fracNDigits=maxlength-1;
> end
> % "%G" format:
> % ANSI specification X3.159-1989: "Programming Language C,"
> % ANSI, 1430 Broadway, New York, NY 10018.
> str=num2str(num,['%0.' num2str(fracNDigits) 'G']);
> %
> % Try to compact the string data to fit inside the field length
> %
> while length(str)>maxlength
> [istart iend]=regexp(str,'[+-](0)+'); % +/- followed by
> multiples 0
> if ~isempty(istart) % Remove zero in xxxE+000yy or
> xxxE-000yy
> str(istart+1:iend)=[];
> continue
> else
> [istart iend]=regexp(str,'E[+]');
> if ~isempty(istart) % Remove "+" char in xxxE+yyy
> str(iend)=[];
> continue
> end
> end
> idot=find(str=='.',1,'first');
> if ~isempty(idot)
> iE=find(str=='E',1,'first');
> if roundingflag % rounding fraction part
> % Calculate the Length of the fractional part
> % Adjust its number of digits and start over again
> if ~isempty(iE) % before the mantissa
> fracNDigits=maxlength-length(str)+iE-idot-1;
> str=num2str(num,['%0.' num2str(fracNDigits)
> 'E']);
> else %if idot<=maxlength+1 % no manissa
> fracNDigits=maxlength-idot;
> str=num2str(num,['%0.' num2str(fracNDigits)
> 'f']);
> end
> roundingflag=0; % won't do rounding again
> continue % second pass with new string
> else
> % truncate the fractional part
> if ~isempty(iE) % before the mantissa
> str(maxlength-length(str)+iE:iE-1)=[];
> return;
> else %if idot<=maxlength+1 % no manissa
> str(maxlength+1:end)=[];
> return;
> end
> end
> end
> % it should not never go here, unless BUG
> error('BuildMPS: cannot convert %0.12e to string\n',num);
> end % while loop
>
> end

I know this is an old thread but I found this function useful and found a major speed improvement:
Replace
str=num2str(num,['%0.' num2str(fracNDigits) 'G']);
with
str=sprintf('%0.*G', fracNDigits, num);

num2str appears several times in the function, so be sure to replace all occurrences. In my case I got over a 2x speed improvement with this change.

Erich