C# 将 int 转换为字符串并填充零?

发布于 2024-10-05 01:20:30 字数 143 浏览 1 评论 0原文

在 C# 中,我有一个整数值需要转换为字符串,但需要在前面添加零:

例如:

int i = 1;

当我将其转换为字符串时,它需要变为 0001

我需要了解 C# 中的语法。

In C# I have an integer value which need to be convereted to string but it needs to add zeros before:

For Example:

int i = 1;

When I convert it to string it needs to become 0001

I need to know the syntax in C#.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

独孤求败 2024-10-12 01:20:31

您可以使用:

int x = 1;
x.ToString("0000");

You can use:

int x = 1;
x.ToString("0000");
别在捏我脸啦 2024-10-12 01:20:31
i.ToString("0000");
i.ToString("0000");
情深已缘浅 2024-10-12 01:20:31

简单易行

int i = 1;
i.ToString("0###")

Easy peasy

int i = 1;
i.ToString("0###")
计㈡愣 2024-10-12 01:20:31

简单地

int i=123;
string paddedI = i.ToString("D4");

Simply

int i=123;
string paddedI = i.ToString("D4");

.NET 在 String 类中提供了一个简单的函数来执行此操作。
只需使用:

.ToString().PadLeft(4, '0')  // that will fill your number with 0 on the left, up to 4 length

int i = 1; 
i.toString().PadLeft(4,'0')  // will return "0001"  

.NET has an easy function to do that in the String class.
Just use:

.ToString().PadLeft(4, '0')  // that will fill your number with 0 on the left, up to 4 length

int i = 1; 
i.toString().PadLeft(4,'0')  // will return "0001"  
瀟灑尐姊 2024-10-12 01:20:31
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
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
如梦初醒的夏天 2024-10-12 01:20:31
public static string ToLeadZeros(this int strNum, int num)
{
    var str = strNum.ToString();
    return str.PadLeft(str.Length + num, '0');
}

// var i = 1;
// string num = i.ToLeadZeros(5);
public static string ToLeadZeros(this int strNum, int num)
{
    var str = strNum.ToString();
    return str.PadLeft(str.Length + num, '0');
}

// var i = 1;
// string num = i.ToLeadZeros(5);
冰雪梦之恋 2024-10-12 01:20:31

大多数给出的答案都很慢或非常慢,或者不适用于负数。

试试这个:

}
    //
    //
    ///<summary>Format a value with a fixed number of digits.</summary>
    public static string Pad( this long v, int digits ) {
        int negative = 0;
        if ( v < 0 ) {
            negative = 1;
            v = Math.Abs( v );
        }
        var source = v.ToString();
        var length = source.Length;
        int max = length;
        if ( max < digits ) {
            max = digits;
        }
        max += negative;
        var ca = new char[ max ];
        for ( int i = 0; i < max; i++ ) {
            ca[ i ] = '0';
        }
        while ( length > 0 ) {
            ca[ --max ] = source[ --length ];
        }
        if ( 0 != negative ) ca[ 0 ] = '-';
        return new string( ca );
    }

Most of the given answers are slow or very slow or don't work for negative numbers.

Try this one:

}
    //
    //
    ///<summary>Format a value with a fixed number of digits.</summary>
    public static string Pad( this long v, int digits ) {
        int negative = 0;
        if ( v < 0 ) {
            negative = 1;
            v = Math.Abs( v );
        }
        var source = v.ToString();
        var length = source.Length;
        int max = length;
        if ( max < digits ) {
            max = digits;
        }
        max += negative;
        var ca = new char[ max ];
        for ( int i = 0; i < max; i++ ) {
            ca[ i ] = '0';
        }
        while ( length > 0 ) {
            ca[ --max ] = source[ --length ];
        }
        if ( 0 != negative ) ca[ 0 ] = '-';
        return new string( ca );
    }
怪异←思 2024-10-12 01:20:31

这里我想用 4 位数字填充我的号码。例如,如果它是 1 那么
它应该显示为 0001,如果是 11,则应该显示为 0011。

下面是完成此操作的代码:

reciptno=1; // Pass only integer.

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

TxtRecNo.Text = formatted; // Output=0001

我实现了此代码来生成 PDF 文件的收款号码。

Here I want to pad my number with 4 digit. For instance, if it is 1 then
it should show as 0001, if it 11 it should show as 0011.

Below is the code that accomplishes this:

reciptno=1; // Pass only integer.

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

TxtRecNo.Text = formatted; // Output=0001

I implemented this code to generate money receipt number for a PDF file.

梦幻的味道 2024-10-12 01:20:31
string hello = "Hello C# Corner.";

string helloHash = hello.PadLeft(5, '#');  

Console.WriteLine(helloHash); 

输出 :-

#####Hello C# Corner.
string hello = "Hello C# Corner.";

string helloHash = hello.PadLeft(5, '#');  

Console.WriteLine(helloHash); 

Output :-

#####Hello C# Corner.
月朦胧 2024-10-12 01:20:31

当两者都可以为负数时,填充 int i 以匹配 int x 的字符串长度:

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

To pad int i to match the string length of int x, when both can be negative:

i.ToString().PadLeft((int)Math.Log10(Math.Abs(x < 0 ? x * 10 : x)) + 1, '0')
橙味迷妹 2024-10-12 01:20:30

i.ToString().PadLeft(4, '0') - 好的,但不适用于负数
i.ToString("0000"); - 显式形式
i.ToString("D4"); - 短格式格式说明符
$"{i:0000}"; - 字符串插值 (C# 6.0+)

i.ToString().PadLeft(4, '0') - okay, but doesn't work for negative numbers
i.ToString("0000"); - explicit form
i.ToString("D4"); - short form format specifier
$"{i:0000}"; - string interpolation (C# 6.0+)

奈何桥上唱咆哮 2024-10-12 01:20:30
i.ToString("D4");

有关格式说明符,请参阅 MSDN

i.ToString("D4");

See MSDN on format specifiers.

小红帽 2024-10-12 01:20:30

这是一个很好的例子:

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

Here's a good example:

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
自由范儿 2024-10-12 01:20:30

C# 6.0 风格的字符串插值

int i = 1;
var str1 = $"{i:D4}";
var str2 = $"{i:0000}";

C# 6.0 style string interpolation

int i = 1;
var str1 = $"{i:D4}";
var str2 = $"{i:0000}";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文