ToString("0") versus ToString(CultureInfo.InvariantCulture)

Jan Zich picture Jan Zich · Sep 28, 2009 · Viewed 22.5k times · Source

I would like to make sure that certain numbers in my application are printed without any separators, groupings etc. no matter what the current environment is. It seems that the following two methods produce the same results (there are possibly more):

123456789.ToString("0");
123456789.ToString(CultureInfo.InvariantCulture);

Are you aware of any edge cases or quirks? Which one is more "correct"? Which one would you use?

I used to use the second one, but recently I found the first one and started using it because it does not require the additional using System.Globalization.

Answer

Jan Zich picture Jan Zich · Sep 29, 2009

Based on the answers and the discussion here, I did some more investigation. Here is what I found:

  • When you use 12345678.ToString() without any arguments, .NET uses general the general format specifier "G" which is affected only by NumberFormatInfo.NegativeSign, NumberFormatInfo. NumberDecimalSeparator, NumberFormatInfo.NumberDecimalDigits and NumberFormatInfo.PositiveSign. To me this says that in any culture 12345678.ToString() should always produce "12345678".

  • If you want to separate digits, you need to use the numeric format specifier "N" (or, of course, to provide a custom format string). The digit grouping also applies to "C" and "P".

  • The invariant culture does indeed specify digit grouping (by 3 digits, of course) and a digit separator. So the reason that 123456789.ToString(CultureInfo.InvariantCulture) produces "123456789" is not because of the invariant culture, but it’s because of the default general numeric format specifier "G".

So I would say that the conclusion is that it’s perfectly OK not to worry about any extra arguments and just use:

12345678.ToString()

I think that this the best from all cases because it means that usually you don’t need to even call ToString() because most of the print/write functions accept all sorts of arguments and do the ToString() for you.