C#创建自定义的NumberFormatInfo显示"免费"当货币值是$ 0.00包装 [英] C# creating a custom NumberFormatInfo to display "Free" when a currency value is $0.00
问题描述
我需要在我的ASP.NET MVC应用程序中显示的货币,但是,当货币是0,我想它来显示自由(局部当然!)代替$ 0.00元。
I need to display a currency in my ASP.NET MVC application but when the currency is 0 I would like it to display "Free" (localized of course!) instead of $0.00.
所以,当我有这样的事情......
So when I have something like this...
Decimal priceFree = 0.00;
Decimal priceNotFree = 100.00;
priceFree.ToString("C");
priceNotFree.ToString("C");
的输出是 $ 0.00 $ 100.00
The output is "$0.00" "$100.00"
我想它是 自由 $ 100.00
I would like it to be "Free" "$100.00"
我想我可以使用的ToString(字符串格式,的IFormatProvider formatProvider)方法来做到这一点,但我不知道如何去做。很明显我想重新使用尽可能多的NumberFormatInfo尽可能只有覆盖它当输入为0。在这种情况下,我可以简单的返回一个本地化的资源,包括我的免费的字符串。
I imagine I can use the .ToString(string format, IFormatProvider formatProvider) method to accomplish this but I'm not sure how to go about it. Obvious I want to reuse as much of the NumberFormatInfo as possible and only override it when the input is 0. In that case I can simple return a localized resource that contains my "Free" string.
那么,如何做到这一点?
So how do I do this?
感谢
推荐答案
我觉得去将是一个扩展方法最简单的方法:
I think the easiest way to go would be an extension method:
public static string ToPriceString(this decimal value)
{
if (value <= 0m)
return "Free"; // Your localized resource
else
return value.ToString("C");
}
如果你想要去的的IFormatProvider
的上有MSDN 的一个很好的例子。
If you want to go with the IFormatProvider
, there is a good example on MSDN.
这篇关于C#创建自定义的NumberFormatInfo显示&QUOT;免费&QUOT;当货币值是$ 0.00包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!