C# 创建自定义 NumberFormatInfo 以显示“Free”当货币价值为 $0.00 时
我需要在 ASP.NET MVC 应用程序中显示货币,但当货币为 0 时,我希望它显示“免费”(当然是本地化的!)而不是 $0.00。
所以当我有这样的东西时......
Decimal priceFree = 0.00;
Decimal priceNotFree = 100.00;
priceFree.ToString("C");
priceNotFree.ToString("C");
输出是 “0.00 美元” “$100.00”
我希望是 “自由的” “$100.00”
我想我可以使用 .ToString(string format, IFormatProvider formatProvider) 方法来完成此任务,但我不知道如何去做。显然,我想尽可能多地重用 NumberFormatInfo,并且仅在输入为 0 时覆盖它。在这种情况下,我可以简单地返回包含我的“Free”字符串的本地化资源。
那么我该怎么做呢?
谢谢
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");
The output is
"$0.00"
"$100.00"
I would like it to be
"Free"
"$100.00"
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?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
Use
我认为最简单的方法是扩展方法:
如果您想使用
IFormatProvider
,MSDN 上有一个很好的示例。I think the easiest way to go would be an extension method:
If you want to go with the
IFormatProvider
, there is a good example on MSDN.扩展方法怎么样:
然后
How about an extension method:
Then
与其使用自定义 IFormatProvider 并每次都传递它,不如这样:
Instead of using a custom IFormatProvider and passing it each time, how about this: