2011-01-13 72 views
1

我有表示捐款量的小数变量。目前,我在屏幕上显示这就像所谓

DonationAmount.ToString("C"); 

这让下面的输出(给予美国地区)

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

我很高兴与前两个例子,但希望货币“0.5”显示为“50c”。

我目前的解决方案是将conditional-

if (DonationAmount > 1) 
    return (DonationAmount * 100m).ToString() + "c"; 
else 
    return DonationAmount.ToString("C"); 

有没有更好的办法?

回答

3

您可以提供自己的自定义格式化(说“仙”),将字符串格式化为“50”。

实现自己IFormatProvider并不难。完成之后,您可以在调用String.Format()ToString()时将其作为参数传递。

这方面的例子可以在这里http://msdn.microsoft.com/en-us/library/system.iformatprovider.aspx或在这里http://www.codeproject.com/KB/cs/custstrformat.aspx找到。

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

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