Search code examples
xamarin.formsdecimalglobalizationcultureinfoculture

Set global cultureinfo for decimal values


How to set CultureInfo globally for all decimal values.

Take one decimal value like

15.00

we may use DecimalValue.ToString("C", new CultureInfo("en-GB"))

so that it will convert for that culture and output is

€15.00

But the question is am I able to Set the culture info for all decimal values that are going to display in the project?


Solution

  • Your better approach is too declare a converter for Decimal values, and use it wherever you need to display the values.

    First you write your converter:

    public class DecimalConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (value == null)
                    return "0";
                decimal decimalValue = (decimal)value;
                return decimalValue.ToString("C", new CultureInfo("en-GB"))
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }
    

    then, in your App.xaml.cs, inside ResourceDictionary you declare it to use it in your application

    Now, in your pages, wherever you bind decimal values, you can use it like this:

       <Label Text="{Binding YourDecimalValue, Converter={StaticResource DecimalConverter}}"/>