2015-03-30 22 views
1

为什么这段代码不能正常工作?我是否误解了某些东西?带括号的C#文本格式化错误

System.Console.WriteLine("{{{0:c}}}", 12323.09m); 

实际产出:

{C}

预期输出:

{$ 12,323.09}

+0

为什么你需要额外的'{}'周围的货币金额 – MethodMan 2015-03-30 20:20:40

+0

令人惊讶的是,这次它实际上是一个C#bug!具体看这个答案:http://stackoverflow.com/a/15085178/369 – Blorgbeard 2015-03-30 20:21:52

+0

var currFormat = string.Format(“{0:c}”,12323.09m);'yeilds' $ 12,323.09' – MethodMan 2015-03-30 20:22:03

回答

0

试试这个:

System.Console.WriteLine("{" + String.Format("{0:C}", 12323.09) + "}");

+0

这是有效的,但实际上并没有回答OP为什么不能按预期工作的问题。 – Blorgbeard 2015-03-30 20:32:18

+2

@Blorgbeard我想你在破译英文方面比我有更多的专业知识。 – user700390 2015-03-30 20:33:45

+0

我想是的。单句中只有几个紧张的错误。 “为什么这个代码不能正确工作?”是明显的“解码”。 – Blorgbeard 2015-03-30 21:58:11

3

问题是{{{0:c}}}被解析为{{{ ... }}},而不是作为{{{ ... }}}

尝试

System.Console.WriteLine("{{{0:c}{1}", 12323.09m, '}'); 

或参见MSDN类似的样品(见逃逸牙套):

int value = 6324; 
string output = string.Format("{0}{1:D}{2}", 
           "{", value, "}"); 
Console.WriteLine(output);