Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# creating a custom NumberFormatInfo to display "Free" when a currency value is $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");

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

like image 539
Justin Avatar asked Nov 29 '22 19:11

Justin


2 Answers

Use

.ToString("$###.00;;Free")
like image 142
Viv Avatar answered Dec 10 '22 02:12

Viv


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.

like image 37
driis Avatar answered Dec 10 '22 03:12

driis