Gaurav Ahuja
Gaurav Ahuja

Reputation: 1105

Comma in string format arguments

I came across the following implementation of ToString() method:

return string.Format("${0}.{1,2:00}", dollars, cents);

I couldn't understand the 2nd command-line argument used in here i.e. {1,2:00} Could somebody please explain the use of , in these arguments?

Upvotes: 2

Views: 185

Answers (1)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61952

See documentation Composite Formatting, and try for example:

result = string.Format("We have '{0,6}' with positive", 3.14);

result = string.Format("We have '{0,-6}' with negative", 3.14);

Quote from linked page:

The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.

Upvotes: 3

Related Questions