Search code examples
c#decimalstring-formatting

Comma as decimal separator space as thousand separator C#


I want to show my decimal type numbers in my WPF DataGrid using comma as decimal and space as thousand separator, with the decimals length of 4 max.

I'm really confused by this StringFormat property, I can't seem to find the meaning of the string I have to specify.

Example:

1234567890.987654 --> 1 234 567 890,988

IMPORTANT EDIT:

The second main part of this question is how to do this in WPF Datagrid, I'll post here, how to change a column's binding from code:

        (stockDataGrid.Columns[1] as DataGridTextColumn).Binding = new Binding("Amount") { ConverterCulture = culture, StringFormat = "c" };

Solution

  • You have to specify both format string and format info:

      decimal source = 1234567890.987654m;
    
      string result = source.ToString(
        "###,###,###,###.###", 
         new NumberFormatInfo() {
           NumberGroupSeparator = " ",
           NumberDecimalSeparator = ","});
    

    If it's too complex and you have to format many currencies in such a way, you can modify the culture:

      CultureInfo culture = CultureInfo.CurrentCulture.Clone() as CultureInfo;
    
      culture.NumberFormat.CurrencyGroupSeparator = " ";
      culture.NumberFormat.CurrencyDecimalSeparator = ",";
      culture.NumberFormat.CurrencySymbol = "";
      culture.NumberFormat.CurrencyDecimalDigits = 3;
      culture.NumberFormat.CurrencyGroupSizes = new int[] {3};
    
      CultureInfo.CurrentCulture = culture;
    
      ...
    
      decimal source = 1234567890.987654m;
    
      string result = source.ToString("c");