Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format currency for different countries

I'm using Xamarin Forms and I tried to format a string (in XAML view) for currency in form: 1.235.436,00 where comma , is the decimal separator. At first, I used StringFormat{0:C2} and result was: $1,235,436.00 which is for US. After, I tried StringFormat{0:#,0.#0}, result: 1,235,436.00.

At last, I tried to use same logic by swapping the dot and comma {0:#.0,#0}, and I got as result: 1235436.000.

So how I can format for currency for France, Spain, Swedish, etc. which is 0.000.000,00 €/kr?

XAML code:

Label Text="{Binding value, StringFormat='{0:C2}.'}"

Which is not correct in my case.

like image 346
Newie Avatar asked Dec 23 '22 09:12

Newie


2 Answers

You cannot do that directly in the binding using StringFormat. You can either implement a custom IValueConverter or create a string property and then implement the formatting in code:

1235436.ToString("C2", CultureInfo.CreateSpecificCulture("es-ES"));

This will format the number as a currency with specific Spanish culture display setting.

You can also modify the a default culture format to force a specific formatting:

var culture = CultureInfo.CreateSpecificCulture("en-US");
culture.NumberFormat.CurrencyDecimalSeparator = ",";
culture.NumberFormat.CurrencyGroupSeparator = ".";

But you should not need to do this. The culture defaults are set in the way in which the users expect the content to be displayed. Changes in the default formats can cause misunderstandings.

like image 65
Martin Zikmund Avatar answered Dec 27 '22 22:12

Martin Zikmund


The format {0:C2} that you used is the right one. To change the format based on the region, you need to change the culture on the thread. It looks like you have it set to the default en-US like you said. You can check it like this:

  CultureInfo current = CultureInfo.CurrentCulture;
  Console.WriteLine("The current culture is {0}", current.Name);

To change it to France:

  CultureInfo.CurrentCulture = new CultureInfo("fr-FR");

And now your value will be automatically formatted like 1.235.436,00.

like image 36
Racil Hilan Avatar answered Dec 27 '22 23:12

Racil Hilan