简体   繁体   中英

What's the difference between ToString(“D2”) .ToString(“00”)

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?

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.

Format D - MSDN

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM