简体   繁体   中英

C# different syntax in formatting numbers

I got a simple question regarding formatting numbers in C#.

I have a format like this

{0:0.00######################}

which was suggested by this website , which basically showing at least 2 decimal places of a number.

Then this website has suggested a different format string

0.00######################

Now, I understand the former and latter have functional differences. For instance, I should use the former in string.Format() calls and the latter in Decimal.ToString() calls. But what I'd like to know is what's the importance in having the curly braces and the

0:

Any ideas?

When you're using String.Format , you can have more than one "item" which will be formatted. This is determined by using {n} where n is the index into the list of values:

var result = string.Format("Arg1 == {0}, Arg2 == {1}", arg1, arg2);

This isn't required with Decimal.ToString and similar since there is only ever one value.

The 0: is really just {0} , and : is used to break out the format specification (everything after the : is effectively the same as what the ToString methods use).

When using String.Format , the curly braces indicate that you are placing a parameter to be replaced by a string. The 0 indicates that it is the first parameter, so for example consider the following:

Console.WriteLine(String.Format("{0} {1} {2}", "A", "B", "C"));

Would output "ABC". Whereas:

Console.WriteLine(String.Format("{2} {0} {1}", "A", "B", "C"));

Would output "CAB".

Hope that helps.

Curly braces is used as a "sign" to be replaced with the value. Number in the curly braces (0 based index) is the index pointing the value.

Example:

string.Format("{0:#,##0} {1:#,##0} {0:#,##0}", 2345, 6789);

Will resulting:

2,345 6,789 2,345

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