Mega Code Archive

 
Categories / Delphi / Forms
 

Displaying the Percentage Character in Delphis Format function

Title: Displaying the Percentage Character in Delphi's Format function Delphi's Format (declared in the SysUtils unit) function can be used to construct a formatted string assembled from a format string and an array of arguments (open array). Declared in two overloads as function Format(const Format: string; const Args: array of const): string; overload; function Format(const Format: string; const Args: array of const; const FormatSettings: TFormatSettings): string; overload; The second version uses the TFormatSettings type variable which refers to localization information contained in the FormatSettings parameter. To display a number, you can use the next code: var s : string; begin s := Format('3 divided with 7 (using 2 decimal places) is %.2f',[3/7]) ; ShowMessage(s) ; Note the usage of the percentage character. The "%.2f" is the format string to be used when formatting the value "3/7" and converting to a string. Displaying the Percentage Sign (%) A beginner Delphi developer might have problems with a line like: Format('In percentage the value is %.2f %',[3/7]) ; The last percentage sign will NOT be a part of the resulting string. To fix this "problem" you simply need to use two % characters, as in Format('In percentage the value is %.2f %%',[3/7]) ; What's more, if you forget about the need to use the two % characters to make the Format function display the percentage sign, aline like this one will result in the "Format '% ' invalid or incompatible with argument". Format('3 % of 7 is %.2f',[3/7]) ; To fix this, simply use two % characters, as in: Format('3 %% of 7 is %.2f',[3/7]) ;