Sakshi Khandelwal
Sakshi Khandelwal

Reputation: 3

Multiple Currency symbols in numberformatinfo

While writing a piece of code, I came across where using Numberformatinfo, I had to write two currency symbols for a country at the same time.

Taiwan, now uses TWD as their currency symbol along with . So they write their Currency as NTD 23,900 起.

But just by using NumberformatInfo, I am not able to put two currency symbols at the same time.

    public NumberFormatInfo GetCurrencyFormat(string countryCode, string languageCode)
    {var cultureInfo = GetCultureInfo(countryCode, languageCode);

        var currencyFormat = GetCurrencyFormat(cultureInfo);
        return currencyFormat;
    }

Here I can change the symbol, but to only one of the above mentioned, which can be placed either before the amount or after.

Upvotes: 0

Views: 472

Answers (1)

Julo
Julo

Reputation: 1120

I'm afraid, there is only one way, how to do this. You need to implement a custom type with a custom formatter.

There seems not be a support for two currency symbols/shortcuts and or one of four predefined formats (see: remarks in documentation)

Simple version can be like this.

using System;
using System.Globalization;

namespace TwoCurrencySymbols
{
  internal sealed class Currency : IFormattable
  {
    private readonly IFormattable value;

    public Currency(IFormattable myValue)
    {
      value = myValue;
    }

    public string ToString(string format, IFormatProvider formatProvider)
    {
      if (format == "C")
      {
        return ("EUR " + value.ToString(format, formatProvider));
      }

      return value.ToString(format, formatProvider);
    }
  }

  internal static class Program
  {
    private static void Main()
    {
      Console.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0:C}", new Currency(1)));
    }
  }
}

The example is constructed for EURO currency (my locale). In your real implementation you need to determine, whether the format should be changed, e.g. if if ((format == "C") && IsTaiwan(formatProvider)).

Upvotes: 1

Related Questions