[英]What's the quickest/best way to format a ?double to currency for string output in C#?
When using .ToString("{blah}") it gives an error because it's a ?double not a double... 'bad parameter' etc 当使用.ToString(“ {blah}”)时会给出错误,因为它是?double而不是double ...'坏参数'等
Note this does not seem to be working, sometimes I get '5.7': 请注意,这似乎不起作用,有时会得到“ 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>";
Have you tried: 你有没有尝试过:
double? myDouble = 10.5;
if (myDouble.HasValue)
{
string currency = myDouble.Value.ToString("c");
}
I find the following to work quite well: 我发现以下工作效果很好:
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
I wouldn't worry too much about performance in this case, and be more concerned with correctness and clarity, myself. 在这种情况下,我不会太担心性能,而我自己会更加关注正确性和清晰度。
I would also suggest you consider using string.Format()
or a StringBuilder
in lieu of concatenating string fragments individually. 我还建议您考虑使用
string.Format()
或StringBuilder
代替单独连接字符串片段。 Not this this is a huge deal, but it does allocate and discard intermediate strings unnecessarily; 这不是什么大不了的事情,但是它确实不必要地分配和丢弃了中间字符串。 which, if you're concerned about performance you'd probably want to eliminate;
其中,如果您担心性能,则可能要消除; for example:
例如:
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.