C# ToString("D2") .ToString("00") 有什么区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13043521/
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
What's the difference between ToString("D2") .ToString("00")
提问by
I just noticed some of my code uses:
我刚刚注意到我的一些代码使用:
ToString("D2")
and other uses:
和其他用途:
.ToString("00")
Both are being used to convert numbers from 0 to 99 into strings from 00 to 99. That is strings where the numbers 0-9 have a leading zero.
两者都用于将 0 到 99 的数字转换为 00 到 99 的字符串。即数字 0-9 具有前导零的字符串。
Do both of these methods do the same thing?
这两种方法做同样的事情吗?
采纳答案by Habib
It is an interesting question. The only difference I have found so far is:
这是一个有趣的问题。到目前为止,我发现的唯一区别是:
format "D2" accepts only integer type values. Where as format "00" would work with floats/doubles as well.
格式“D2”只接受整数类型值。格式“00”也适用于浮点数/双精度数。
Supported by: Integral types only.
支持者:仅积分类型。
Consider the following three lines:
考虑以下三行:
double d = 23.05123d;
int i = 3;
Console.Write(i.ToString("D2"));
Console.Write(d.ToString("00"));
Console.Write(d.ToString("D2")); //this will result in exception:
//Format specifier was invalid.
回答by nick_w
From MSDN Custom Numeric Format Strings:
The "00" specifier causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "00" would result in the value 35.
“00”说明符使值四舍五入到小数点前最接近的数字,其中始终使用远离零的四舍五入。例如,使用“00”格式化 34.5 将导致值 35。
And MSDN Standard Numeric Format Strings:
The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier.
精度说明符指示结果字符串中所需的最小位数。如果需要,数字在其左侧填充零以生成精度说明符给出的位数。
So to answer your question, according to the docs these don't specificallydo the same thing, but in you case it is possible that they are intended to. For example:
因此,为了回答您的问题,根据文档,这些并没有专门做同样的事情,但在您的情况下,它们可能是有意为之。例如:
double d = 3.678;
Console.WriteLine(d.ToString("00"));
Console.WriteLine(4.ToString("D2"));
Will both print out 04. I would imagine those two formats are being used because D2is not valid for doubles.
都会打印出来04。我想这两种格式正在被使用,因为D2它对双打无效。

