Format currency with symbol before instead of after

1.2k views Asked by At

I use a Converter for my TextBox for currency. Everything works great, except that the €-sign is after the value instead of before.

Here is the code:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    var dValue = value as decimal?;
    return string.Format(CultureInfo.GetCultureInfo("de-DE"), "{0:C}", dValue ?? 0);
}

I know I can easily put it before it instead of after like so:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    var dValue = value as decimal?;
    return "€ " + string.Format(CultureInfo.GetCultureInfo("de-DE"), "{0:C}", dValue ?? 0).Replace("€", "").Trim();
}

But I'm just assuming here that there should be a standard in the formatter itself to do this. So, does anyone know how to put the currency before the value instead of behind it using the formatter itself?

For example: With the decimal 12345678.90, I don't want to display [see first method] 12.345.678,90 €, but I want to display [see second method] € 12.345.678,90 instead.

2

There are 2 answers

0
faby On BEST ANSWER

try in this way

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    var dValue = value as decimal?;
    Thread.CurrentThread.CurrentCulture = new CultureInfo("de");
    var nfi = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
    nfi.CurrencySymbol = "€";
    return string.Format(nfi,"{0:c}",dValue)
}

if it doesn't work try without this line

Thread.CurrentThread.CurrentCulture = new CultureInfo("de");

if it doesn't work again try changing CurrencyNegativePattern Property and CurrencyPositivePattern Property with the value of 2

nfi.NumberFormat.CurrencyPositivePattern = 2;
nfi.NumberFormat.CurrencyNegativePattern = 2;

2 means "€ + number"

0
Michael On

Try this (quick code, not really a unit test method, just to see the output).

[Test]
public void CurrencySymbolShouldAppearBeforeValue()
{
    decimal price = 1370m;
    var formatInfo = CultureInfo.GetCultureInfo("de-DE")
                                .NumberFormat.Clone() as NumberFormatInfo;

    Assert.IsNotNull(formatInfo);

    formatInfo.CurrencyPositivePattern = 2;

    string formated = price.ToString("C3", formatInfo);
    Assert.IsNotNull(formated);
}

Outputs: € 1.370,000

You can read more here.