C# creating a custom NumberFormatInfo to display “Free” when a currency value is $0.00

∥☆過路亽.° 提交于 2019-12-12 12:03:08

问题


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


回答1:


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");
}

If you want to go with the IFormatProvider, there is a good example on MSDN.




回答2:


Use

.ToString("$###.00;;Free")



回答3:


How about an extension method:

public static string FreeString(this decimal dec)
{
   if(dec == 0M)
   {
      return "Free";
   }
   else
   {
      return dec.ToString("C");
   }
}

Then

priceFree.FreeString();
priceNotFree.FreeString();



回答4:


Instead of using a custom IFormatProvider and passing it each time, how about this:

 public static class MyFormatter
    {
        public static string ToFreeString(this decimal d)
        {
            return d == 0 ? "Free" : d.ToString("d");
        }
    }


来源:https://stackoverflow.com/questions/3866796/c-sharp-creating-a-custom-numberformatinfo-to-display-free-when-a-currency-val

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!