2 char int 上的 C# int ToString 格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9281078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:41:54  来源:igfitidea点击:

C# int ToString format on 2 char int?

c#tostring

提问by Ray

How do I use the ToString method on an integer to display a 2-char

如何在整数上使用 ToString 方法来显示 2 个字符

int i = 1; i.ToString() -> "01" instead of "1"

int i = 1; i.ToString() -> "01" instead of "1"

Thanks.

谢谢。

采纳答案by Patrick McDonald

You can use i.ToString("D2")or i.ToString("00")

您可以使用i.ToString("D2")i.ToString("00")

See Standard Numeric Format Stringsand Custom Numeric Format Stringson Microsoft Docsfor more details

请参阅标准数字格式字符串自定义数字格式字符串微软文档了解更多详情

回答by Chris Trombley

This should do it:

这应该这样做:

String.Format("{0:00}",i);

Here's a link to an msdn article on using custom formatting strings: http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

以下是有关使用自定义格式字符串的 msdn 文章的链接:http: //msdn.microsoft.com/en-us/library/0c899ak8.aspx

回答by rerun

i.ToString("00")Take a look at thisfor more rules.

i.ToString("00")看看this了解更多规则。

回答by JaredPar

In order to ensure at least 2 digits are displayed use the "00"format string.

为了确保至少显示 2 位数字,请使用"00"格式字符串。

i.ToString("00");

Here is a handy reference guide for all of the different ways numeric strings can be formatted

这是一个方便的参考指南,用于格式化数字字符串的所有不同方式

回答by Mayer Spitzer

In any case you wanna check first if it's only 1 number, use Regular Expression:

在任何情况下,您都想先检查它是否只有 1 个数字,请使用正则表达式:

Regex OneNumber = new Regex("^[0-9]$");
OneNumber.Replace(i.ToString(), "0" + i)

回答by Steve

In C# 6 you could write:

在 C# 6 中,你可以这样写:

var i = 1;
var stringI = $"{i:D2}";

$ - string interpolation

$ - 字符串插值