Rodney
Rodney

Reputation: 5565

String Format expression to show Currency with 2 decimal places only if there are decimals (.net)

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)

Upvotes: 3

Views: 3743

Answers (2)

Eugene Cheverda
Eugene Cheverda

Reputation: 8930

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;

FBTMoVGogot

Upvotes: 1

Oded
Oded

Reputation: 499002

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.

Upvotes: 4

Related Questions