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
Note this does not seem to be working, sometimes I get '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.Descripti开发者_StackOverflow社区on + "</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. 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 );
Use decimals for handling your currency values, and Decimal.ToString("C") for formatting.
OK it looks like this is working:
((double)theVariable).ToString("c");
精彩评论