Format函数使用示例(谢谢)(100分)

  • 主题发起人 主题发起人 恭喜发才
  • 开始时间 开始时间

恭喜发才

Unregistered / Unconfirmed
GUEST, unregistred user!
发几个示例吧,看一下!
 
var
i: integer;
tt: string;
begin
i := 10;
tt := ForMat('i = %d', );
showmessage(tt);

showmessage(Format('%*.*f', [8, 2, 123.456]));
showmessage(Format('%8.2f', [123.456]));
end;
 
Format('%8.2f', [123.456]);
 
var
s: string;
begin
s := '%s的工资是%d元/月';
s := Format(s,['王二',10000]);
showmessage(s);
end;
 
delphi里面的帮助已经很全了啊,为什么不看?
Format strings specify required formats to general-purpose formatting routines.

Description

Format strings passed to the string formatting routines contain two types of objects -- literal characters and format specifiers. Literal 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:

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

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

An optional argument zero-offset index specifier (that is, the first item has index 0), [index ":"]
An optional left justification indicator, ["-"]
An optional width specifier, [width]
An optional precision specifier, [".&quot
prec]
The conversion type character, type

The following table summarizes the possible values for type:

d Decimal. The argument must be an integer value. The value is converted to a string of decimal 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.
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. 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梐 default precision of 15 is assumed if no precision specifier is present. The "E&quot
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梐 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梐 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&quot
format corresponds to the "f&quot
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 or their equivalent in a TFormatSettings data structure. If the format string contains a precision specifier, it overrides the value given by the CurrencyDecimals global variable or its TFormatSettings equivalent.
p Pointer. The argument must be a pointer value. The value is converted to an 8 character string that represents the pointers value in hexadecimal.
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 fewer digits, the resulting string is left-padded with zeros.
Conversion characters may be specified in uppercase as well as in lowercase梑oth 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 or their TFormatSettings equivalent.
Index, width, and precision specifiers can be specified directly using 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,

Delphi example:

Format('%*.*f', [8, 2, 123.456]);

is equivalent to

Format('%8.2f', [123.456]);

C++ example:

TVarRec args[3] = {8,2,123.456};
Format("%*.*f", args, 2);

is equivalent to

TVarRec args[1] = {123.456};
Format("%8.2f", args, 0);

A width specifier sets the minimum field width for a conversion. If the resulting string is shorter than the minimum field width, it 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 "-&quot
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 %1:d', [10, 20])&quot
produces the string '10 20 10 20'.

Note: Setting the index specifier affects all subsequent formatting. That is, Format('%d %d %d %0:d %d', [1, 2, 3, 4]) returns '1 2 3 1 2', not '1 2 3 1 4'. To get the latter result, you have must use Format('%d %d %d %0:d %3:d', [1, 2, 3, 4])
 
http://blog.csdn.net/VBEND/archive/2005/01/24/265641.aspx

function Format(const Format: string
const Args: array of const): string
$[SysUtils.pas
功能 返回按指定方式格式化一个数组常量的字符形式
说明 这个函数是我在Delphi中用得最多的函数,现在就列举几个例子给你个直观的理解
"%&quot
[索引 ":"] ["-"] [宽度] [".&quot
摘要] 类型
Format('x=%d', [12])
//'x=12' //最普通
Format('x=%3d', [12])
//'x= 12' //指定宽度
Format('x=%f', [12.0])
//'x=12.00' //浮点数
Format('x=%.3f', [12.0])
//'x=12.000' //指定小数
Format('x=%8.2f'[12.0]) // 'x= 12.00' ;
Format('x=%.*f', [5, 12.0])
//'x=12.00000' //动态配置
Format('x=%.5d', [12])
//'x=00012' //前面补充0
Format('x=%.5x', [12])
//'x=0000C' //十六进制
Format('x=%1:d%0:d', [12, 13])
//'x=1312' //使用索引
Format('x=%p', [nil])
//'x=00000000' //指针
Format('x=%1.1e', [12.0])
//'x=1.2E+001' //科学记数法
Format('x=%%', [])
//'x=%' //得到"%"
S := Format('%s%d', [S, I])
//S := S + StrToInt(I)
//连接字符串
==========
,C Char, strings Character. Shows characters for ASCII 0 to 31 in the Delphi language #nn notation.
,S Char, strings String. Shows ASCII 0 to 31 in Delphi language #nn notation.
,D Integers Decimal. Shows integer values in decimal form, including those in data structures.
,H or ,X Integers Hexadecimal. Shows integer values in hexadecimal with the $ prefix, including those in data structures.
,Fn Floating point Floating point. Shows n significant digits where n can be from 2 to 18. For example, to display the first four digits of a floating-point value, type ,F4. If n is not specified, the default is 11.

,P Pointers Pointer. Shows pointers as 32-bit addresses with additional information about the address pointed to. It tells you the region of memory in which the pointer is located and, if applicable, the name of the variable at the offset address.

,R Records, classes, Records/Classes/Objects. Shows both field names and

objects values such as (X:1;Y:10;Z:5) instead of (1,10,5).

,nM All Memory dump. Shows n bytes, starting at the address of the indicated expression.
For example, to display the first four bytes starting at the memory address, type 4M.
If n is not specified, it defaults to the size in bytes of the type of the variable.
By default, each byte is displayed as two hex digits.
Use memory dump with the C, D, H, and S format specifiers to change the byte formatting.
 
function Format(const Format: string
const Args: array of const): string
overload;
事实上Format方法有两个种形式,另外一种是三个参数的,主要区别在于它是线程安全的,
但并不多用,所以这里只对第一个介绍:

function Format(const Format: string
const Args: array of const): string
overload;
Format参数是一个格式字符串,用于格式化Args里面的值的。Args又是什么呢,
它是一个变体数组,即它里面可以有多个参数,而且每个参数可以不同。
如以下例子:
Format('my name is %6s',['wind']);
返回后就是
my name is wind

现在来看Format参数的详细情况:
Format里面可以写普通的字符串,比如'my name is'
但有些格式指令字符具有特殊意义,比如"%6s"

格式指令具有以下的形式:
"%&quot
[index ":"] ["-"] [width] [".&quot
prec] type
它是以"%"开始,而以type结束,type表示一个具体的类型。中间是用来
格式化type类型的指令字符,是可选的。

先来看看type,type可以是以下字符:
d 十制数,表示一个整型值
u 和d一样是整型值,但它是无符号的,而如果它对应的值是负的,则返回时
是一个2的32次方减去这个绝对值的数
如:Format('this is %u',[-2]);
返回的是:this is 4294967294
f 对应浮点数
e 科学表示法,对应整型数和浮点数,
比如Format('this is %e',[-2.22]);
返回的是:this is -2.22000000000000E+000
等一下再说明如果将数的精度缩小
g 这个只能对应浮点型,且它会将值中多余的数去掉
比如Format('this is %g',[02.200]);
返回的是:this is 2.2
n 只能对应浮点型,将值转化为号码的形式。看一个例子就明白了
Format('this is %n',[4552.2176]);
返回的是this is 4,552.22
注意有两点,一是只表示到小数后两位,等一下说怎么消除这种情况
二是,即使小数没有被截断,它也不会也像整数部分一样有逗号来分开的
m 钱币类型,但关于货币类型有更好的格式化方法,这里只是简单的格式化
另外它只对应于浮点值
Format('this is %m',[9552.21]);
返回:this is ¥9,552.21
p 对应于指针类型,返回的值是指针的地址,以十六进制的形式来表示
例如:
var X:integer;
p:^integer;
begin
X:=99;
p:=@X;
Edit1.Text:=Format('this is %p',[p]);
end;
Edit1的内容是:this is 0012F548
s 对应字符串类型,不用多说了吧
x 必须是一个整形值,以十六进制的形式返回
Edit1.Text:=Format('this is %X',[15]);
返回是:this is F

类型讲述完毕,下面介绍格式化Type的指令:
[index ":"] 这个要怎么表达呢,看一个例子
Format('this is %d %d',[12,13]);
其中第一个%d的索引是0,第二个%d是1,所以字符显示的时候
是这样 this is 12 13

而如果你这样定义:
Format('this is %1:d %0:d',[12,13]);
那么返回的字符串就变成了
this is 13 12
现在明白了吗,[index ":"] 中的index指示Args中参数显示的
顺序

还有一种情况,如果这样Format('%d %d %d %0:d %d', [1, 2, 3, 4])
将返回1 2 3 1 2。
如果你想返回的是1 2 3 1 4,必须这样定:
Format('%d %d %d %0:d %3:d', [1, 2, 3, 4])
但用的时候要注意,索引不能超出Args中的个数,不然会引起异常
如Format('this is %2:d %0:d',[12,13]);
由于Args中只有12 13 两个数,所以Index只能是0或1,这里为2就错了
[width] 指定将被格式化的值占的宽度,看一个例子就明白了
Format('this is %4d',[12]);
输出是:this is 12
这个是比较容易,不过如果Width的值小于参数的长度,则没有效果。
如:Format('this is %1d',[12]);
输出是:this is 12
["-"] 这个指定参数向左齐,和[width]合在一起最可以看到效果:
Format('this is %-4d,yes',[12]);
输出是:this is 12 ,yes

[".&quot
prec] 指定精度,对于浮点数效果最佳:
Format('this is %.2f',['1.1234]);
输出 this is 1.12
Format('this is %.7f',['1.1234]);
输了 this is 1.1234000

而对于整型数,如果prec比如整型的位数小,则没有效果
反之比整形值的位数大,则会在整型值的前面以0补之
Format('this is %.7d',[1234]);
输出是:this is 0001234]

对于字符型,刚好和整型值相反,如果prec比字符串型的长度大
则没有效果,反之比字符串型的长度小,则会截断尾部的字符
Format('this is %.2s',['1234']);
输出是 this is 12

而上面说的这个例子:
Format('this is %e',[-2.22]);
返回的是:this is -2.22000000000000E+000
怎么去掉多余的0呢,这个就行啦
Format('this is %.2e',[-2.22]);

好了,第一个总算讲完了,应该对他的应用很熟悉了吧

///////////////////////////////////////////////////////////////
二 FormatDateTime的用法
他的声明为:
function FormatDateTime(const Format: string
DateTime: TDateTime): string

overload;
当然和Format一样还有一种,但这里只介绍常用的第一种
Format参数是一个格式化字符串。DateTime是时间类型。返回值是一种格式化后的
字符串

重点来看Format参数中的指令字符
c 以短时间格式显示时间,即全部是数字的表示
FormatdateTime('c',now);
输出为:2004-8-7 9:55:40
d 对应于时间中的日期,日期是一位则显示一位,两位则显示两位
FormatdateTime('d',now);
输出可能为1~31
dd 和d的意义一样,但它始终是以两位来显示的
FormatdateTime('dd',now);
输出可能为01~31
ddd 显示的是星期几
FormatdateTime('ddd',now);
输出为: 星期六
dddd 和ddd显示的是一样的。
但上面两个如果在其他国家可能不一样。
ddddd 以短时间格式显示年月日
FormatdateTime('ddddd',now);
输出为:2004-8-7
dddddd 以长时间格式显示年月日
FormatdateTime('dddddd',now)

输出为:2004年8月7日
e/ee/eee/eeee 以相应的位数显示年
FormatdateTime('ee',now)

输出为:04 (表示04年)
m/mm/mmm/mmmm 表示月
FormatdateTime('m',now);
输出为:8
FormatdateTime('mm',now);
输出为 08
FormatdateTime('mmm',now);
输出为 八月
FormatdateTime('mmmm',now)

输出为 八月
和ddd/dddd 一样,在其他国家可能不同
yy/yyyy 表示年
FormatdateTime('yy',now);
输出为 04
FormatdateTime('yyyy',now);
输出为 2004
h/hh,n/nn,s/ss,z/zzz 分别表示小时,分,秒,毫秒
t 以短时间格式显示时间
FormatdateTime('t',now);
输出为 10:17
tt 以长时间格式显示时间
FormatdateTime('tt',now);
输出为10:18:46
ampm 以长时间格式显示上午还是下午
FormatdateTime('ttampm',now);
输出为:10:22:57上午

大概如此,如果要在Format中加普通的字符串,可以用双引号隔开那些
特定义的字符,这样普通字符串中如果含特殊的字符就不会被显示为
时间格式啦:
FormatdateTime('"today is&quot
c',now);
输出为:today is 2004-8-7 10:26:58
时间中也可以加"-"或"/"来分开日期:
FormatdateTime('"today is&quot
yy-mm-dd',now);
FormatdateTime('"today is&quot
yy/mm/dd',now);
输出为: today is 04-08-07
也可以用":"来分开时间
FormatdateTime('"today is&quot
hh:nn:ss',now);
输出为:today is 10:32:23

/////////////////////////////////////////////////////////////////
三.FormatFloat的用法

常用的声明:
function FormatFloat(const Format: string
Value: Extended): string
overload;
和上面一样Format参数为格式化指令字符,Value为Extended类型
为什么是这个类型,因为它是所有浮点值中表示范围最大的,如果传入该方法的参数
比如Double或者其他,则可以保存不会超出范围。

关键是看Format参数的用法
0 这个指定相应的位数的指令。
比如:FormatFloat('000.000',22.22);
输出的就是022.220
注意一点,如果整数部分的0的个数小于Value参数中整数的位数,则没有效果
如:FormatFloat('0.00',22.22);
输出的是:22.22
但如果小数部分的0小于Value中小数的倍数,则会截去相应的小数和位数
如:FormatFloat('0.0',22.22);
输出的是:22.2

也可以在整数0中指定逗号,这个整数位数必须大于3个,才会有逗号出句
FormatFloat('0,000.0',2222.22);
输出是:2,222.2
如果这样FormatFloat('000,0.0',2222.22);
它的输出还是:2,222.2
注意它的规律

# 和0的用法一样,目前我还没有测出有什么不同。
FormatFloat('##.##',22.22);
输出是:22.00

E 科学表示法,看几个例子大概就明白了
FormatFloat('0.00E+00',2222.22);
输出是 2.22E+03
FormatFloat('0000.00E+00',2222.22);
输出是 2222.22E+00
FormatFloat('00.0E+0',2222.22);
22.2E+2
 
This example displays a message on the form抯 status bar indicating the dataset抯 record count after a record is deleted.

procedure TForm1.ClientDataSet1AfterDelete(DataSet: TDataSet);
begin
StatusBar1.SimpleText := Format('There are now %d records in the table', [DataSet.RecordCount]);
end;
 
我经常用Formatfloat,感觉这个特方便的
 
多人接受答案了。
 
后退
顶部