[英]What's the quickest/best way to format a ?double to currency for string output in C#?
當使用.ToString(“ {blah}”)時會給出錯誤,因為它是?double而不是double ...'壞參數'等
請注意,這似乎不起作用,有時會得到“ 5.7”:
double itemListPrice = Math.Round((double)((item.UserIntervalPrice * item.Volume) -
((item.UserIntervalPrice * item.Volume) * (item.VolumeDiscount / 100))),2);
htmlReceipt += "<tr><td>" + item.Title + "</td><td>" + item.Description + "</td><td>" +
item.Volume + "</td><td>$" + itemListPrice.ToString() + "</td></tr>";
你有沒有嘗試過:
double? myDouble = 10.5;
if (myDouble.HasValue)
{
string currency = myDouble.Value.ToString("c");
}
我發現以下工作效果很好:
double? val1 = null;
double? val2 = 5.7d;
var s1 = string.Format("{0:c}", val1); // outputs: ""
var s2 = string.Format("{0:c}", val2); // outputs: $5.70
在這種情況下,我不會太擔心性能,而我自己會更加關注正確性和清晰度。
我還建議您考慮使用string.Format()
或StringBuilder
代替單獨連接字符串片段。 這不是什么大不了的事情,但是它確實不必要地分配和丟棄了中間字符串。 其中,如果您擔心性能,則可能要消除; 例如:
htmlReceipt +=
string.Format( "<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3:c}</td></tr>",
item.Title, item.Description, item.Volume, item.listPrice );
使用小數來處理貨幣值,並使用Decimal.ToString(“ C”)進行格式化。
好吧,看起來像這樣工作:
((double)theVariable).ToString("c");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.