Search code examples
c#decimalcustom-formatting

How would I separate thousands with space in C#


Assume I have the following decimal number that I have to format so that every thousand should be separated with a space:

 897.11 to 897.11
 1897.11 to 1 897.11
 12897.11 to 12 897.11
 123897.11 to 123 897.11

I have tried Decimal.ToString("0 000.00"). Although this works pretty well when the number is 1897.11. But when it's 897.11 I get 0 897.11.


Solution

  • Pass in a custom NumberFormatInfo with a custom NumberGroupSeparator property, and use the #,# format to tell it to do number groups. This example uses the invariant culture's number format as its basis.

    var nfi = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();
    nfi.NumberGroupSeparator = " ";
    string formatted = 1234897.11m.ToString("#,0.00", nfi); // "1 234 897.11"