views:

89

answers:

2

Silverlight 4/C#: I have a label showing a number formatted in the Currency (with 2 decimal places) of the thread culture, e.g.

25 shows as $25.00 and 25.01 shows as $25.01

I use "StringFormat=C2" for this. My problem is... I only want to show the 2 decimal places IF there are decimal places. e.g.

25 should show as $25 and 25.01 should show as $25.01

With a normal number I would use # - eg. #.## and that supresses the decimals if they don't exist, but then I don't get the Currency symbol. C2.## does not work.

Any suggestions please? (Hardcoding currency symbol is not an option)

A: 
decimal value = 1603.42m;
var temp = string.Empty;
if (Decimal.Floor(value) < value) //means value is with decimal part
    temp = value.ToString("C2", new CultureInfo("en-US"));
else
    temp = value.ToString("C0", new CultureInfo("en-US"));
return temp;
Eugene Cheverda
+1  A: 

Check whether the decimal contains a fractional element and return a different representation depending on the result:

public string GetFormatStringForDecimal(myDec){
    return (Decimal.Ceiling(myDec) > myDec) ? "C2" : "C0";
}

This function will return a format string for your decimal as specified in your question.

Oded
return type will be string
Eugene Cheverda
@Eugene Cheverda - of course it is... that's how I wrote the function and named it... thanks for catching this silly error.
Oded
Thanks - I like this solution - I am using the new Silverlight 4 binding format - Text="{Binding TotalValueInPlay, StringFormat=C}" I'll have to see if that can call public methods...
Rodney
Ok, in the end I had to revert back to a Converter instead of using the StringFormat that I wanted to, but I used this code in the converter - thanks!
Rodney
@Rodney - glad I could help :)
Oded