String.Format does not provide correct result for number format
c#, string-formatting
Solution
Yes, the ouptut given is perfectly right and your understanding is also right that `{`, `}` in `string.Format` should be escaped by `{`, `}` respectively and to format string in Number you have to use `{0:N}`.
But when you are looking for output `{95.00}` the format `{{{0:N}}}` do not work as expected, for this we should undesrstand how the above statement is interpreted,
- The first two curly brackets are escaped as we understand `{` followed by `{`,
prints `{` at output
- Then we have a formatting section `{0:N}}}` but compiler is confused that `}` is ending brace of `{0:N` or it is escaped brace as it is followed by `}` which result in formation of custom format `0:N}`. but rules say it should be considered as custom format, thus it is actually interpreted as containing `0:N}`
- Since neither `N` or `}` mean anything for a custom numeric format, these characters are simply written out, rather than the value of the variable referenced.
Thus we have output, `{N}`.
The detail explanation for above can be found at string Format FAQ
If you are looking for output `{95.00}` then either use `{{ {0:N} }}` and it will provide `95.00` as output with space.
EDIT The solution by Heinzi is perfectly right for the output you are expecting,
Console.WriteLine(String.Format("{0}{1:N}{2}", "{", myNumber, "}"));
Problem
Why does the following output provide incorrect result, ``` int myNumber = 95; Console.WriteLine(String.Format("{{{0:N}}}", myNumber )); ``` Output is `{N}` rather then `{95.00}` as expected. Am I misunderstanding the concept of escaping `{` `}` or doing something wrong with Number format?