Reputation: 21
What do the values within the curly brackets do in this example?
{
double price = 1234.56
Console.WriteLine("TV{0:F0} is {1:C}" , 2, price);
Console.Read();
}
Upvotes: 2
Views: 1586
Reputation: 24525
What do the values within the curly brackets do in this example?
They are format specifications for the values provided. Essentially, it instructs the Console.WriteLine
function how to format the values as strings for output to the console. Here is a .NET fiddle that exemplifies this.
The MSDN documentation has an extensive example that shows how these work.
{0:F0}
takes the given 2
int value, and simply prints it as 2
, "2"{1:C}
takes the given 1234.56
double value and treats it as currency, "$1,234.45".The 0
and 1
are significant as they are the zero-based array indicator of the location in which the parameters map to the string formatting. For example, the below demonstrates outputs from altering the arguments to better visualize the impact.
Console.WriteLine("TV{0:F0} is {1:C}", 2, price); // Prints TV2 is $1,234.56
Console.WriteLine("TV{0:F0} is {1:C}", price, 2); // Prints TV1234 is $2.00
Upvotes: 0
Reputation: 9649
Basically the first number ist the index of the argument (0
means 2
, 1
means price
in your example).
The value after the colon is one of the Standard Numeric Format Strings, see MSDN-Docs for available options.
{0:F0}
prints 2
because parameter 0 is 2
and format is Fixed Point with zero decimal places (F0
) {1:C}
prints $1234,56
becaus parameter 1 (price
) is 1234.56
and format is Currency (C
)This example uses only Format Strings for numerics, there are also Standard Format Strings for DateTime
and so on..
Upvotes: 3