开发者

handling leading zeros in C#

开发者 https://www.devze.com 2023-01-30 03:55 出处:网络
I have a field1 that should 开发者_运维问答not be more than 7 characters. The remaining characters in field1 should be filled with leading zeros.

I have a field1 that should 开发者_运维问答not be more than 7 characters. The remaining characters in field1 should be filled with leading zeros.

If field1 is 1 then it should be converted to 0000001. If field1 is 21 then it should be converted to 0000021.

How do i do this in C#. Please help.


If you have a number and you want a string representation of 7 digits, pretty simple.

1.ToString("0000000");

Say you have any particular string and you want to pad it to 7 characters, and those characters happen to be same character, you can do that, too.

1.ToString().PadLeft(7, '0');


Use a format specifier:

 string x = string.Format("{0:0000000}", 21);


Another solution would be to use Standard Numeric Format Strings like this:

5.ToString("D7")

And to prevent having integers with more than 7 characters, modulo can be used like this:

(123456789 % 10000000).ToString("D7")

Modulo should be faster than cutting of additional characters in the resulting string.

Thus every integer will result in a 7 character string filled with up with zeros.

0

精彩评论

暂无评论...
验证码 换一张
取 消