RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
AnsiStrings.Format Function

Format argument list using format string.

Pascal
function Format(const Format: AnsiString; const Args: array of const): AnsiString; overload;
function Format(const Format: AnsiString; const Args: array of const; const FormatSettings: TFormatSettings): AnsiString; overload;
C++
AnsiString Format(const AnsiString Format, const array of const Args);
AnsiString Format(const AnsiString Format, const array of const Args, const TFormatSettings FormatSettings);

The Format routine formats the argument list given by the Args parameter using the format string given by the Format parameter.  

Format strings contain two types of objects: plain characters and format specifiers. Plain characters are copied verbatim to the resulting string. Format specifiers fetch arguments from the argument list and apply formatting to them.  

Format specifiers have the following form:

% ["index" :] [-] ["width"] [. "prec"] "type"

A format specifier begins with a % character. After the % come the following, in this order:

  1. an optional argument index specifier, ["index" :]
  2. an optional left-justification indicator, [-]
  3. an optional width specifier, ["width"]
  4. an optional precision specifier, [. "prec"]
  5. the required conversion type character, "type"

The following conversion characters are supported:

Value 
Meaning 
d  
Decimal. The argument must be an integer value. The value is converted to a string of decimal digits. The resulting string starts with a minus sign if the number is negative. If the format string contains a precision specifier, it indicates that the resulting string must contain at least the specified number of digits; if the value has less digits, the resulting string is left-padded with zeros.  
u  
Unsigned decimal. Similar to d, but no sign is output.  
e  
Scientific. The argument must be a floating-point value. The value is converted to a string of the form "-d.ddd...E+ddd". The resulting string starts with a minus sign if the number is negative, and one digit always precedes the decimal point. The total number of digits in the resulting string (including the one before the decimal point) is given by the precision specifier in the format string; a default precision of 15 is assumed if no precision specifier is present. The "E" exponent character in the resulting string is always followed by a plus or minus sign and at least three digits.  
f  
Fixed. The argument must be a floating-point value. The value is converted to a string of the form "-ddd.ddd...". The resulting string starts with a minus sign if the number is negative. The number of digits after the decimal point is given by the precision specifier in the format string; a default of 2 decimal digits is assumed if no precision specifier is present.  
g  
General. The argument must be a floating-point value. The value is converted to the shortest possible decimal string using fixed or scientific format. The number of significant digits in the resulting string is given by the precision specifier in the format string; a default precision of 15 is assumed if no precision specifier is present. Trailing zeros are removed from the resulting string, and a decimal point appears only if necessary. The resulting string uses fixed point format if the number of digits to the left of the decimal point in the value is less than or equal to the specified precision and if the value is greater than or equal to 0.00001. Otherwise, the resulting string uses scientific format.  
n  
Number. The argument must be a floating-point value. The value is converted to a string of the form "-d,ddd,ddd.ddd...". The n format corresponds to the f format, except that the resulting string contains thousand separators.  
m  
Money. The argument must be a floating-point value. The value is converted to a string that represents a currency amount. The conversion is controlled by the CurrencyString, CurrencyFormat, NegCurrFormat, ThousandSeparator, DecimalSeparator, and CurrencyDecimals global variables, all of which are initialized from locale settings provided by the operating system. For example, currency format preferences can be set in the International section of the Windows Control Panel. If the format string contains a precision specifier, it overrides the value given by the CurrencyDecimals global variable.  
p  
Pointer. The argument must be a pointer value. The value is converted to a string of the form "XXXX:YYYY" where XXXX and YYYY are the segment and offset parts of the pointer expressed as four hexadecimal digits.  
s  
String. The argument must be a character, a string, or a PChar value. The string or character is inserted in place of the format specifier. The precision specifier, if present in the format string, specifies the maximum length of the resulting string. If the argument is a string that is longer than this maximum, the string is truncated.  
x  
Hexadecimal. The argument must be an integer value. The value is converted to a string of hexadecimal digits. If the format string contains a precision specifier, it indicates that the resulting string must contain at least the specified number of digits. If the value has less digits, the resulting string is left-padded with zeros.  

Conversion characters may be specified in upper case as well as in lower case; both produce the same results. 

For all floating-point formats, the actual characters used as decimal and thousand separators are obtained from the DecimalSeparator and ThousandSeparator global variables.  

Index, width, and precision specifiers can be specified directly using a decimal digit string (for example "%10d"), or indirectly, using an asterisk character (for example "%*.*f"). When using an asterisk, the next argument in the argument list (which must be an integer value) becomes the value that is actually used. For example, Format('%*.*f', [8, 2, 123.456]) is the same as Format('%8.2f', [123.456]).  

A width specifier sets the minimum field width for a conversion. If the resulting string is shorter than the minimum field width, the string is padded with blanks to increase the field width. The default is to right-justify the result by adding blanks in front of the value, but if the format specifier contains a left-justification indicator (a "-" character preceding the width specifier), the result is left-justified by adding blanks after the value.  

An index specifier sets the current argument list index to the specified value. The index of the first argument in the argument list is 0. Using index specifiers, it is possible to format the same argument multiple times. For example Format('%d %d %0:d %d', [10, 20]) produces the string '10 20 10 20'.  

The Format function can be combined with other formatting functions. For example:

S := Format('Your total was %s on %s', [ 
    FormatFloat('$#,##0.00;;zero', Total),
                FormatDateTime('mm/dd/yy', Date)]); 

This code uses the FormatFloat and FormatDateTime functions to customize the format beyond what is possible with the Format function. 

Each of the string formatting routines that uses global variables for formatting (separators, decimals, date/time formats, etc.) has an overloaded equivalent requiring a parameter of type TFormatSettings. This additional parameter provides the formatting information rather than the global variables. For more information, see the documentation for TFormatSettings.  

C++ Examples: 

 

/*
This example copies a specified old file to a new file.  Add
a TSaveDialog to the form.  Also add two TEdits, two TLabels
and a TButton with the OnClick event named Save1Click. Change
the Old Path and New Path to move files outside the Debug
directory, Old File and New File will not take a relative path.
*/

#include <memory>       //for STL auto_ptr class

void __fastcall TForm1::Save1Click(TObject *Sender)
{
  AnsiString temp1 = Edit4->Text;
  AnsiString temp2 = ExtractFileName(Edit1->Text);
  AnsiString NewFileName = temp1 + temp2;
  AnsiString OldFileName =
    Edit3->Text + ExtractFileName(Edit2->Text);
  AnsiString Msg = Format("Copy %s to %s", ARRAYOFCONST((OldFileName, NewFileName)));
  if (MessageDlg(Msg, mtCustom, TMsgDlgButtons() << mbOK << mbCancel, 0) == mrOk)
  {
    std::auto_ptr<TFileStream> OldFile(new TFileStream(OldFileName, fmOpenRead | fmShareDenyWrite));
    std::auto_ptr<TFileStream> NewFile(new TFileStream(NewFileName, fmCreate | fmShareDenyRead));
    NewFile->CopyFrom(OldFile.get(), OldFile->Size);
  }
}

void __fastcall TForm1::FormCreate(TObject *Sender)
{
  Edit3->Text = ExtractFilePath(Application->ExeName);
  Edit4->Text = Edit3->Text;
}
/*
This example displays a message on the form’s status bar
indicating the record count after a record is deleted.  Set
the StatusBar SimplePanel property to True.
*/
void __fastcall TForm1::Table1AfterDelete(TDataSet *DataSet)
{
  StatusBar1->SimpleText = Format(
    "There are now %d records in the table",
    ARRAYOFCONST(((int)DataSet->RecordCount)));
}

void __fastcall TForm1::Button1Click(TObject *Sender)
{
  Table1->Delete();
}

void __fastcall TForm1::FormCreate(TObject *Sender)
{
  Table1 = new TTable(Form1);
  Table1->Active = false; // The Table component must not be active
  Table1->DatabaseName = "DBDEMOS";
  Table1->TableType = ttParadox;
  Table1->TableName = "CustInfo";
  Table1->Active = False;
  if (!Table1->Exists) // Don't overwrite an existing table
  {
    Table1->Close();
    Table1->DeleteTable();
  }
  // The Table component must not be active
  // First, describe the type of table and give
  // it a name
  // Next, describe the fields in the table
  Table1->FieldDefs->Clear();
  TFieldDef *pNewDef = Table1->FieldDefs->AddFieldDef();
  pNewDef->Name = "Field1";
  pNewDef->DataType = ftInteger;
  pNewDef->Required = true;
  pNewDef = Table1->FieldDefs->AddFieldDef();
  pNewDef->Name = "Field2";
  pNewDef->DataType = ftString;
  pNewDef->Size = 30;
  // Next, describe any indexes
  Table1->IndexDefs->Clear();
  /* the 1st index has no name because it is a Paradox primary key */
  Table1->IndexDefs->Add("","Field1", TIndexOptions() <<ixPrimary << ixUnique);
  Table1->IndexDefs->Add("Fld2Index","Field2", TIndexOptions() << ixCaseInsensitive);
  // Now that we have specified what we want, create the table
  Table1->CreateTable();
  Table1->Active = True;
  for (int i = 1; i <= 20; i++)
    Table1->AppendRecord(ARRAYOFCONST((i*111, i*222)));
  DS2->DataSet = Table1;
  DBGrid2->DataSource->DataSet = Table1;
  Table1->AfterDelete = Table1AfterDelete;
  Table1->Active = True;
}

 

Delphi Examples: 

{
This example copies a specified old file to a new file.  Add
a TSaveDialog to the form.  Also add two TEdits, two TLabels
and a TButton with the OnClick event named Save1Click. Change
the Old Path and New Path to move files outside the Debug
directory, Old File and New File will not take a relative path.
}
procedure TForm1.FormCreate(Sender: TObject);
begin
  Edit3.Text := ExtractFilePath(Application.ExeName);
  Edit4.Text := Edit3.Text;
end;

procedure TForm1.Save1Click(Sender: TObject);
var
  NewFileName, OldFileName: string;
  temp1, temp2: string;
  Msg: string;
  NewFile: TFileStream;
  OldFile: TFileStream;
begin
  temp1 := Edit4.Text;
  temp2 := ExtractFileName(Edit1.Text);
  NewFileName := temp1 + temp2;
  OldFileName :=
    Edit3.Text + ExtractFileName(Edit2.Text);
  Msg := Format('Copy %s to %s?', [OldFileName, NewFileName]);
  if MessageDlg(Msg, mtCustom, mbOKCancel, 0) = mrOK then
  begin
    OldFile := TFileStream.Create(
      OldFileName, fmOpenRead or fmShareDenyWrite);
    try
      NewFile := TFileStream.Create(
        NewFileName, fmCreate or fmShareDenyRead);
      try
        NewFile.CopyFrom(OldFile, OldFile.Size);
      finally
        FreeAndNil(NewFile);
      end;
    finally
      FreeAndNil(OldFile);
    end;
  end;
end; 

 

{
This example displays a message on the form’s status bar
indicating the record count after a record is deleted.  Set
the StatusBar SimplePanel property to True.
}
procedure TForm1.Table1AfterDelete(DataSet: TDataSet);
begin
  StatusBar1.SimpleText := Format('There are now %d records in the table', [DataSet.RecordCount]);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Table1.Delete;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  i: Integer;
begin
  Table1:= TTable.Create(Form1);
  with Table1 do
  begin
    DatabaseName := 'DBDEMOS';
    TableType := ttParadox;
    TableName := 'CustInfo';
    Name := 'CustInfo';
    Table1.Active := False;
    { Don't overwrite an existing table }
    if Table1.Exists then
    begin
        Table1.Close;
        Table1.DeleteTable;
    end;
    begin
      { The Table component must not be active }
      { First, describe the type of table and give }
      { it a name }
      { Next, describe the fields in the table }
      with FieldDefs do
      begin
        Clear;
        with AddFieldDef do
        begin
          Name := 'Field1';
          DataType := ftInteger;
          Required := True;
        end;
        with AddFieldDef do
        begin
          Name := 'Field2';
          DataType := ftString;
          Size := 30;
        end;
      end;
      { Next, describe any indexes }
      with IndexDefs do
      begin
        Clear;
        { The 1st index has no name because it is
        { a Paradox primary key }
        with AddIndexDef do
        begin
          Name := '';
          Fields := 'Field1';
          Options := [ixPrimary];
        end;
        with AddIndexDef do
        begin
          Name := 'Fld2Indx';
          Fields := 'Field2';
          Options := [ixCaseInsensitive];
        end;
      end;
      { Call the CreateTable method to create the table }
      CreateTable;
      Table1.Active:= True;
      for i := 1 to 20 do
        Table1.AppendRecord([i*111, i*222]);
    end;
  end;
  DS2.DataSet:= Table1;
  DBGrid2.DataSource.DataSet:= Table1;
  Table1.AfterDelete:= Table1AfterDelete;
  Table1.Active:= True;
end;

 

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!