From: Theo Olsthoorn on
Is there any way to force output of g and f format to stay within the specified field with. This is giving me trouble all the time and at ever unexpected locations when preparing input for fortran programs that require 10 width numbers

Matlab is completely uncontrollable in this respect. Writing my own formatting function is not an option because I need to write out multimillion numbers each time. This would bring Matlab to its knees.

Example:

fprintf('%10g %10f',123456789.123456789,123456789.123456789)
1.23457e+008 123456789.123457

Thanks

Theo Olsthoorn, TUDelft, Netherlands
From: Walter Roberson on
Theo Olsthoorn wrote:
> Is there any way to force output of g and f format to stay within the
> specified field with. This is giving me trouble all the time and at ever
> unexpected locations when preparing input for fortran programs that
> require 10 width numbers

> fprintf('%10g %10f',123456789.123456789,123456789.123456789)
> 1.23457e+008 123456789.123457

The %10 is the *minimum* field width. To get closer control, use a
precision specification, such as %10.4g .

For %f format, the precision is the number of digits to add after the
decimal point. Add one to count the decimal point, subtract that count
from the field width, and you get the mininum umber of characters
(including spaces) that will appear to the left of the decimal (not sure
of that includes a leading negative.) If the number of digits that exist
to the left of the decimal point exceed that available width, then the
number actually needed will be used. Matlab doe NOT convert numbers to a
field of asterisks if the number exceeds what can be printed in the
given width.

For %g format, the precision specifies the number of significant digits,
including the one before the decimal point. It does not, however,
include any character needed for an exponent.

If you look at the documentation, you can see a couple of ways to zero
fill to get precise field widths for %g .
http://www.mathworks.com/access/helpdesk/help/techdoc/ref/fprintf.html