Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why specify culture in String conversion [duplicate]

Tags:

c#

Resharper is warning me that I need to specify a string culture when doing an int.ToString()

For example:

int Value = Id.ToString(); // Where Id is an int

Is this just resharper being pedantic, or is there a reason I need to give a culture setting for converting an int to a string?

And if there is a reason to do this - what is the best to use, when my site is used around the globe? Should it just reflect the server settings, so that the internal conversion is done safely?

like image 637
Craig Avatar asked Apr 05 '14 22:04

Craig


2 Answers

Because, for example, English cultures use '.' as a decimal point, where as French cultures use ',' and the opposite to separate thousands. Specifying a culture removes this ambiguity so that code executes identically on Windows operating systems configured for different languages, particularly if the parsed values are being committed to persistent storage.

like image 90
Martin Costello Avatar answered Oct 20 '22 08:10

Martin Costello


The reason is that the string representation of a number vary from country to country.

Some use a '.' as the thousand separator, some use ',', some just doesn't use any symbol at all.

The ToString overload with no parameter uses the current culture so your output will vary depending on the computer's settings.

That said, my rule of thumb is:

  • every internal representation must be InvariantCulture (never relay on server settings!)
  • everything on the presentation must use end user's locale

Hope it helps

like image 43
Manuel Spezzani Avatar answered Oct 20 '22 06:10

Manuel Spezzani