serhio
serhio

Reputation: 28586

String.Format in .NET

I have a little problem on the string formatting in .NET

?String.Format("{00} {1}", 1, "min")
"1 min"

I need the output "01 min" but "20 min" if instead the 1 I have 20.

Upvotes: 1

Views: 112

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499660

The problem is that you're using "00" as if it's the format specifier, but it's actually just the index part of the format item. You want:

String.Format("{0:00} {1}", 1, "min")

So within {0:00} the first part (0) is the index, and second part (00) is the format string. See the MSDN page on composite formatting for more information.

Or you could use:

String.Format("{0:d2} {1}", 1, "min")

Where d2 is a standard numeric format string with 2 as the precision specifier.

Upvotes: 5

Related Questions