2010-12-01 114 views
327

在C#我有需要要轉換爲字符串的整數值,但它需要前加零:C#將int轉換爲帶填充零的字符串?

例如:

int i = 1; 

當我把它轉換成需要成爲0001

我需要知道C#中的語法。

+1

這可能會幫助你 - [如何:使用前導零填充數字](http://msdn.microsoft.com/en-us/library/dd260048.aspx)。祝您好運 – cadmuxe 2010-12-01 14:23:44

回答

517

i.ToString().PadLeft(4, '0') - 還行,但對於負數不起作用
i.ToString("0000"); - 顯性形式
i.ToString("D4"); - 短表格式說明

+18

i.ToString()。PadLeft(4,'0')不適用於負數,例如(-5).PadLeft(4,'0')將是「00-5」 – 2013-05-21 14:58:57

+4

如何顯示一個固定長度的字符串。 ?? – 2014-11-12 10:34:49

+3

@Rahul閱讀此:https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx#FFormatString – Kevdog777 2015-02-04 14:51:29

61

您可以使用:

int x = 1; 
x.ToString("0000"); 
18
i.ToString("0000"); 
246
i.ToString("D4"); 

請參閱格式說明符上的MSDN

101

這裏有一個很好的例子:

int number = 1; 
//D4 = pad with 0000 
string outputValue = String.Format("{0:D4}", number); 
Console.WriteLine(outputValue);//Prints 0001 
//OR 
outputValue = number.ToString().PadLeft(4, '0'); 
Console.WriteLine(outputValue);//Prints 0001 as well 
1

你也可以使用擴展

寫一個靜態的擴展類,並簡單地使用它:

public static class Extensions 
{ 
    public static string IntToStringWithLeftPad(this int number) 
    { 
     return number.ToString("D4"); 
    } 
} 

,並用它喜歡:

 int i = 3; 
     string padStr = i.ToStringWithLeftPad(); 
-2

要墊int i匹配的int x字符串長度,當兩個可以是負數:

i.ToString().PadLeft((int)Math.Log10(Math.Abs(x < 0 ? x * 10 : x)) + 1, '0') 
16

C#6.0風格的字符串插值

int i = 1; 
var str1 = $"{i:D4}"; 
var str2 = $"{i:0000}"; 
0
int p = 3; // fixed length padding 
int n = 55; // number to test 

string t = n.ToString("D" + p); // magic  

Console.WriteLine("Hello, world! >> {0}", t); 

// outputs: 
// Hello, world! >> 055 
-1

在這裏,我想我沒有在4位數限制就像它是1它應該顯示爲0001,如果它11應該顯示爲0011..BOLOW是代碼。

reciptno=1;//Pass only integer. 

    string formatted = string.Format("{0:0000}", reciptno); 

    TxtRecNo.Text = formatted;//Output=0001.. 

我實現了這個代碼來生成錢收據沒有PDF格式。