Home >Backend Development >C++ >How to Add Leading Zeros to an Integer When Converting to a String in C#?

How to Add Leading Zeros to an Integer When Converting to a String in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-25 22:18:13440browse

How to Add Leading Zeros to an Integer When Converting to a String in C#?

Convert integer to string with leading zeros in C#

In C#, to convert an integer to a string with leading zeros, you can use several methods:

1. ToString().PadLeft(n, '0'): (not recommended for negative numbers) This method accepts two parameters: the desired string length (n) and the characters used for padding ('0' means zero). It pads the integer on the left with zeros to the specified length.

<code class="language-C#">int i = 1;
var zeroPaddedString = i.ToString().PadLeft(4, '0');
// 输出: "0001"</code>

2. ToString("0000"): Explicit format This format explicitly specifies the desired format as a string with a specific number of zeros.

<code class="language-C#">int i = 1;
var zeroPaddedString = i.ToString("0000");
// 输出: "0001"</code>

3. ToString("D4"): Concise format specifier The "D" format specifier is used for positive integers. It implicitly right-pads the number with zeros to fit the specified length.

<code class="language-C#">int i = 1;
var zeroPaddedString = i.ToString("D4");
// 输出: "0001"</code>

4. String interpolation ($"{i:0000}"): (C# 6.0 only) String interpolation provides a concise string formatting syntax. The expression :"0000" specifies the required format for the integer.

<code class="language-C#">int i = 1;
var zeroPaddedString = $"{i:0000}";
// 输出: "0001"</code>

The above is the detailed content of How to Add Leading Zeros to an Integer When Converting to a String in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn