When I try the below code, I get the output 2 084 001. What could be wrong here? Isn’t my format string supposed to override the current culture settings?
decimal v = 2084000.7621m;
System.Console.WriteLine(v.ToString("#,###,###"));
System.Console.ReadLine();
If I modify the code to use ToString("#,###,###", CultureInfo.InvariantCulture), I get the expected output, i.e. 2,084,001 but I cannot specify a format provider when I set the DataFormatString property on my data bound controls.
WARNING: When using an escaped literal group separator, as described below in the accepted and other answers, the literal character used is always output, even if it isn’t needed, e.g. applying the format string #\,###\,### to a value of 324 results in an output value of ,,324.
As far as I understand the Custom Numeric Format Strings, the
,symbol is to place the group separator into the formatting (and not to specify which character to use). To make it an explicit symbol, you need to use the escape character\.Which has the disadvantage that the format string depends on the size of the number. In this case, you always get two commas in the resulting string, even if the number is smaller or higher.
To override the group separator, you need to specify your own
NumberFormatInfo.Got this test working:
It actually doesn’t matter where and how many group separators you put into the format string. You could also make it:
"#,#.####"with the exact same result. (Thats the advantage of using the group separator character, in contrast to the first solution).