当使用.ToString(“{blah}”)时,它会给出一个错误,因为它是一个双倍而不是双重...'错误参数'等
注意这似乎不起作用,有时我得到'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>";
答案 0 :(得分:3)
你试过了吗?
double? myDouble = 10.5;
if (myDouble.HasValue)
{
string currency = myDouble.Value.ToString("c");
}
答案 1 :(得分:2)
我发现以下内容非常有效:
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 );
答案 2 :(得分:1)
使用小数处理货币值,使用Decimal.ToString("C")进行格式化。
答案 3 :(得分:0)
好吧,看起来这样可行:
((double)theVariable).ToString("c");