开发者

Format decimal to currency, should be in cents for values $0 to $1

I have a decimal variable which represents a donation amount. Currently I am displaying it on screen as a currency like so-

DonationAmount.ToString("C");

This gives the following output (given a US locale)

1 -> $1.00
2 -> $2.00
0.5 -> $0.50

I am happy with the first two example, but want to have "0.5" show as "50c".

My current solution is with a conditional-

if (DonationAmount > 1)
  开发者_JS百科 return (DonationAmount * 100m).ToString() + "c";
else
   return DonationAmount.ToString("C");

Is there a better way?


You can provide your own Custom Formatter (say "cents") that will format the string as "50c".

Implementing your own IFormatProvider is not that difficult. Once you've done that, you would then pass it as a parameter when calling String.Format() or ToString().

Examples of this can be found here http://msdn.microsoft.com/en-us/library/system.iformatprovider.aspx or here http://www.codeproject.com/KB/cs/custstrformat.aspx.

public class StringFormatInfo : IFormatProvider, ICustomFormatter
{
   ...
}

return number.ToString("{0:cents}", new StringFormatInfo());
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜