Reputation:
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.
Do both of these methods do the same thing?
Upvotes: 53
Views: 62105
Reputation: 14938
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.
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 specifically do 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 D2
is not valid for doubles.
Upvotes: 14
Reputation: 223322
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.
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.
Upvotes: 53