Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 567
Jan Zich Avatar asked Sep 28 '09 14:09

Jan Zich


People also ask

What does CultureInfo Invariantculture mean?

The invariant culture is culture-insensitive; it is associated with the English language but not with any country/region. You specify the invariant culture by name by using an empty string ("") in the call to a CultureInfo instantiation method. CultureInfo.

What is ToString N0?

ToString("N0") is supposed to print the value with comma separators and no decimal points.

What is numeric formatting in C#?

The numeric ("N") format specifier converts a number to a string of the following form − "-d,ddd,ddd.ddd…" Above, "-" is a negative number symbol if required, "d" is a digit (0-9), "," indicates a group separator, "." is a decimal point symbol.


1 Answers

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.

like image 172
Jan Zich Avatar answered Sep 22 '22 04:09

Jan Zich