Re: Format function in Delphi

Posted by webmaster Guido on August 22, 2005

In Reply to: Write Delphi array of string posted by robert on August 20, 2005

: I want to write array of string and of float in a textfile align in the left margin the first.
: write(f1,format('%10s',[MyArray[i]]), format('%1.2f',[myArray2[i]]));
: but I get
: abcdefg 1.22
: **aabnv 3.12
: ***alak 6.23
:
: i want to mean blank when using *
: and i need write
:
: abcdefg 1.22
: aabnv 3.12
: alak 6.23

By default, in Delphi the function Format returns strings that are RIGHT aligned. For LEFT alignment you have to specify a - character after the % (for example: '%-10s').

Also note that if you write '%1.2f' this means a total WIDTH of only 1 and a PRECISION of 2.
WIDTH must provide positions for the entire number. In other words, for a PRECISION of 2 you should use at least '%4.2' for positive numbers that are smaller than 10.

A few examples:

WriteLn(F1, Format('%10s', [MyArray[i]]), Format('%4.2f',[myArray2[i]])) gives:

 abcdefg1.22
   abcde3.12
    abcd6.23 

WriteLn(F1, Format('%-10s', [MyArray[i]]), Format('%5.2f',[myArray2[i]])) gives:

abcdefg   1.22
abcde     3.12
abcd      6.23 

In the format specifier, WIDTH is optional. If you don't know the maximum size, you'd better not use it. You can use a space ' ' to separate the strings, as in this example:

WriteLn(F1, Format('%-s', [MyArray[i]]), ' ', Format('%.2f',[myArray2[i]])) gives:

abcdefg 1.22
abcde 3.12
abcd 6.23

Related Articles and Replies