I have the following number: 4.3
I\'d like to display this number as 4,3
for some of our European friends.
I was under the impressi
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ",";
nfi.NumberGroupSeparator = ".";
double num = 4.3;
string ret = num.ToString(nfi); // 4,3
Number formatting can be handled for you by the framework if you use the correct culture when manipulating the number.
Console.WriteLine(4.3);
Console.WriteLine(4.3.ToString(CultureInfo.GetCultureInfo("fr-fr")));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("fr-fr");
Console.WriteLine(4.3);
If you want to do a "one-off" display, the second approach will work. If you want to display every number correctly, you really should be setting the current thread's culture. That way, any number manipulation will handle decimal separators, grouping characters and any other culture-specific things correctly.
The same goes for parsing numbers. If a user enters 1,234
, how do you know whether they have entered 1.234
(the comma being the decimal separator) or 1234
(the comma being a grouping separator)? This is where the culture helps out as it knows how to display numbers and can also be used to parse them correctly:
Console.WriteLine(double.Parse("1,234"));
Console.WriteLine(double.Parse("1,234", CultureInfo.GetCultureInfo("fr-fr")));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("fr-fr");
Console.WriteLine(double.Parse("1,234"));
The above will output 1234
(the comma is a decimal separator in my en-us default culture), 1.234
(the comma is a decimal separator in French) and 1,234
(again, the comma is a decimal separator in French, and also the thread's culture is set To French so it displays using this culture - hence the comma as a decimal separator in the output).
The number formatting by default uses the NumberFormatInfo from the current CultureInfo, so that it displays using the regional settings on the computer.
Therefore, you don't really need to do anything special about it, except maybe making sure that the correct CultureInfo is being used.
As for the question, yes the string is invalid. A "," denotes a thousand-separator, not the decimal-separator. Have a look the the NumberFormatInfo and the custom number formats.