tags:

views:

119

answers:

4

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.Description + "</td><td>" + 
    item.Volume + "</td><td>$" + itemListPrice.ToString() + "</td></tr>";
+3  A: 

Have you tried:

double? myDouble = 10.5;

if (myDouble.HasValue)
{
    string currency = myDouble.Value.ToString("c");
}
Darin Dimitrov
Note: outputting as currency includes formatting such as currency symbol, as defined on the current thread's culture information.
Jon Seigel
Sure, thought that's what the OP is after.
Darin Dimitrov
@Darin: Yes, but his output formatting currently includes a hard-coded currency symbol.
Jon Seigel
+2  A: 

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 );
LBushkin
+1  A: 

Use decimals for handling your currency values, and Decimal.ToString("C") for formatting.

Ian Gregory
+1. `Double` and `currency` should never appear in the same sentence together, unless there's also the words "do not use" somewhere in between.
Pavel Minaev
A: 

OK it looks like this is working:

((double)theVariable).ToString("c");
shogun