5

I know we can escape curly bracket in C# using {{ and }}. But they don't seem to work well if they are right after a format modifier (like {0:F6}).

string str;

// Prints "{3.14}" as expected
str = string.Format("{{{0}}}", 3.14);
Console.WriteLine(str);

// Expected "{3.140000}", found "{F6}"
str = string.Format("{{{0:F6}}}", 3.14);
Console.WriteLine(str);
6
  • 2
    Why don't you just str = "{" + string.Format("{0:F6}", 3.14) + "}"; Commented Dec 10, 2015 at 17:19
  • 2
    @Pikoh i think the question is more about "is this intended behaviour in c#" Commented Dec 10, 2015 at 17:20
  • @blas3nik's answer explains why; see also MSDN "Escaping Braces" in "Composite Formatting" where it is clearly explained; specifically "interpreting nested braces is not supported". Commented Dec 10, 2015 at 17:27
  • pi =~ 3.14159265... so you would want 3.141593 Commented Dec 10, 2015 at 17:37
  • kludge str = "{" + string.Format("{0:F6}", 3.14) + "}"; Console.WriteLine(str); Commented Dec 10, 2015 at 17:43

2 Answers 2

6

This is how C# processes curly brackets, it's well known. See here

You can escape it like this (for example, there are different ways):

 var str = string.Format("{0}{1:F6}{2}", "{", 3.14, "}");
 Console.WriteLine(str);
Sign up to request clarification or add additional context in comments.

4 Comments

thanks for the link - something to remember if I ever come across this. I'd upvote this twice if I could.
Your answer is correct (+1) but I'd definitely call this a bug that Microsoft simply never fixed.
@xxbbcc its not a bug. F6}} is taken as format of variable. btw it would be nice if they make it non-greedy ;)
@M.kazemAkhgary Yes, I read the linked article and I meant that the greediness of the implementation is the bug.
1

Try this:

 String.Format("{0}{1:F6}{2}", "{",3.14, "}") 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.