开发者

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 pla开发者_运维百科ces) 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)


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜