Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a string with string.Format("{0:00}"

Tags:

I have just taken over some code and I see this used a lot. It seems to take the integer and create a string looking like "01", "02" etc.

What I am not sure of is the convention used here. Why is the format {0:00} and not {00}?

string.Format("{0:00}", int.Parse(testVal) + 1); 
like image 697
David H Avatar asked Jun 15 '11 03:06

David H


Video Answer


2 Answers

The first 0 is the placeholder, means the first parameter. 00 is an actual format.

For example it could be like this:

var result = string.Format("{0:00} - {1:00}", 5, 6); 

result will be 05 - 06. So the first 0 is means take the first parameter 5, while 1 means to take parameter 6.

The format is {index[,length][:formatString]}. Take a look at String.Format Method.

like image 67
Alex Aza Avatar answered Sep 27 '22 21:09

Alex Aza


The first 0 in the following line is for the index of your argument

string.Format("{0:00}", int.Parse(testVal) + 1);  

(int.Parse(testVal) + 1).ToString ("00") will yield the same thing.

string.Format supports multiple substitutions like this:

string.Format("{0:00} + 1 = {1:00}", int.Parse(testVal), int.Parse(testVal) + 1);  
like image 35
agent-j Avatar answered Sep 27 '22 20:09

agent-j