Formatting Numbers as Strings with Commas in place of Decimals

后端 未结 9 605
离开以前
离开以前 2020-12-03 07:46

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

9条回答
  •  忘掉有多难
    2020-12-03 08:48

    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).

提交回复
热议问题