Space as thousands separator for labels

1.3k Views Asked by At

I have a label and im using binding and a FormatString as such:

<Label Text="{Binding buying_price , StringFormat='{0} EUR'}">

The label's text is bound to a double in my ViewModel, what im getting on the label is something like this: 10000 EUR, what i want to get is 10 000 EUR, and 12 501 005 EUR for example (without the trailing .00). I tried StringFormat='{0:C2} EUR' and StringFormat='{0:N} EUR' and StringFormat='{0:n} EUR' but non of them gave me a good result.

2

There are 2 best solutions below

0
On BEST ANSWER

I did not make it work in xaml, while when I use a convert and use string format in code behind, it works as excepted:

<ContentPage.Resources>
    <ResourceDictionary>
        <local:thousandsSeparatorConverter x:Key="thousandsSeparator"/>
    </ResourceDictionary>
</ContentPage.Resources>

<StackLayout>
    <!-- Place new controls here -->
    <Label Text="{Binding date, Converter={StaticResource thousandsSeparator}}"  HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"/>
    
</StackLayout>

And the local:thousandsSeparatorConverter :

public class thousandsSeparatorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string s = value as string;


        double number = double.Parse(s);

        // Gets a NumberFormatInfo associated with the en-US culture.
        NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;

        // Displays the same value with a blank as the separator.
        nfi.NumberGroupSeparator = " ";
        Console.WriteLine(number.ToString("N0", nfi));

        string convertedNumber = number.ToString("N0", nfi);

        return convertedNumber;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }

}
0
On

Try using StringFormat='{}{0:#,##,#}' depending on your culture you may need to change it in the code-behind if you get a result of 10,000 EUR instead of 10 000 EUR, in the former the , is a thousands separator not a comma.

You may want to take a look at the complete documentation for available numeric format string.

Related question helpful for culture: How would I separate thousands with space in C#