如何将前导零添加到数字(Delphi格式)

Different applications require specific values to conform to structural paradigms. For example, Social Security numbers are always nine digits long. Some reports require that numbers be displayed with a fixed amount of characters. Sequence numbers, for example, usually start with 1 and increment without end, so they're displayed with leading zeroes to present a visual appeal.

不同的应用程序需要特定的值以符合结构范例。 例如,社会安全号码始终为9位数字。 某些报告要求数字显示时要使用固定数量的字符。 例如,序列号通常以1开头,无尾递增,因此它们以前导零显示,以显示视觉效果。

As a Delphi programmer, your approach to adding a number with leading zeroes depends on the specific use case for that value. You can simply opt to pad a display value, or you can convert a number to a string for storage in a database.

作为Delphi程序员 ,您添加前导零的数字的方法取决于该值的特定用例。 您可以选择填充显示值,也可以将数字转换为字符串以存储在数据库中。

显示填充方法 ( Display Padding Method )

Use a straightforward function to change how your number displays. Use format to make the conversion by supplying a value for length (the total length of the final output) and the number you want to pad:

使用简单的功能即可更改您的数字显示方式。 使用格式通过提供长度值(最终输出的总长度)和您要填充的数字来进行转换:

str := Format('%.*d,[length, number])

To pad the number 7 with two leading zeroes, plug those values into the code:

要用两个前导零填充数字7,请将这些值插入代码中:

str := Format('%.*d,[3, 7]);

The result is 007 with the value returned as a string. 

结果为007 ,其值作为字符串返回。

转换为字符串方法 ( Convert to String Method )

Use a padding function to append leading zeroes (or any other character) any time you need it within your script. To convert values that are already integers, use:

在脚本中需要时,可使用填充函数附加前导零(或任何其他字符)。 要转换已经是整数的值,请使用:

function LeftPad(value:integer; length:integer=8; pad:char='0'): string; overload; 
begin
   result := RightStr(StringOfChar(pad,length) + IntToStr(value), length ); 
end;

If the value to be converted is already a string, use:

如果要转换的值已经是字符串,请使用:

function LeftPad(value: string; length:integer=8; pad:char='0'): string; overload;
begin
   result := RightStr(StringOfChar(pad,length) + value, length );
end;

This approach works with Delphi 6 and later editions. Both of these code blocks default to a padding character of with a length of seven returned characters; those values may be modified to meet your needs.

这种方法适用于Delphi 6和更高版本。 这两个代码块均默认为填充字符0 ,长度为7   返回的字符; 可以修改这些值以满足您的需求。

When LeftPad is called, it returns values according to the specified paradigm. For example, if you set an integer value to 1234, calling LeftPad:

调用LeftPad时,它将根据指定的范例返回值。 例如,如果将整数值设置为1234,则调用LeftPad:

i:= 1234;r := LeftPad(i);

i:= 1234; r:= LeftPad(i);

will return a string value of 0001234.

将返回字符串值0001234

翻译自: https://www.thoughtco.com/add-leading-zeroes-number-delphi-format-1057555

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值