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?
Your understanding is correct: Use two braces to create a single literal brace. The problem, however, is that in the string }}}
, the first two braces are interpreted as a literal brace, rather than the second and the third, as you intended.
In fact, your example is explicitly listed on the corresponding MSDN page as a possible problem (highlighting by me):
The way escaped braces are interpreted can lead to unexpected results. For example, consider the format item "{{{0:D}}}", which is intended to display an opening brace, a numeric value formatted as a decimal number, and a closing brace. However, the format item is actually interpreted in the following manner:
...
- The next character ("D") would be interpreted as the Decimal standard numeric format specifier, but the next two escaped braces ("}}") yield a single brace.
The suggested solution is to use something like this:
int myNumber = 95;
Console.WriteLine(String.Format("{0}{1:N}{2}", "{", myNumber, "}"));
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,
{
followed by {
,
prints
{
at output
{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}
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, "}"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With