Question:
In C#, you need to convert an integer to a string with leading zeros in front of it. For example, when converting the integer 1 to a string, it should be formatted as 0001.
Solution:
To perform this conversion in C#, there are several ways:
ToString().PadLeft method:
<code class="language-csharp"> int i = 1; string paddedString = i.ToString().PadLeft(4, '0'); // 输出 "0001"</code>
Please note that this method may not handle negative numbers correctly.
Explicit formatting:
<code class="language-csharp"> int i = 1; string paddedString = i.ToString("0000"); // 输出 "0001"</code>
This method explicitly defines the required format.
Abbreviated format specifier:
<code class="language-csharp"> int i = 1; string paddedString = i.ToString("D4"); // 输出 "0001"</code>
The "D" format specifier is shorthand for number formatting, where the specified number represents the minimum number of digits to be displayed.
String interpolation (C# 6.0):
<code class="language-csharp"> int i = 1; string paddedString = $"{i:0000}"; // 输出 "0001"</code>
String interpolation provides a concise way to format strings, including number formatting using placeholders.
The above is the detailed content of How to Convert Integers to Zero-Padded Strings in C#?. For more information, please follow other related articles on the PHP Chinese website!