2015-03-30 39 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);