用几行代码处理整个程序的小数分隔符(逗号和点)

Handling decimal separators (comma and dot) for a whole program with few lines of code

我正在努力使我的程序更兼容,为此我最终改变了很多小东西,例如,

使用 textBox.Text = Convert.ToString(value) 代替 = "value"

获取当前用户小数点分隔符并在 tryparse

上使用它 replace
char sepdec = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);

float.TryParse(str.Replace(",", sepdec.ToString()).Replace(".", sepdec.ToString()), out testvariable;

但是当您已经对大部分程序进行编码而不用担心时,这些解决方案很难实施。

所以我试图找到使整个代码兼容的方法,而不必编辑每个 tryparse 和每个 textbox

我已尝试执行以下操作:

//Get the current user decimal separator before the program initializes
char sepdec = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);

//Create a current culture clone and change the separator to whatever the user has in his regional options, before the initializing the component

  public Form1()
  {
  System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
  customCulture.NumberFormat.NumberDecimalSeparator = sepdec.ToString();

  System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;

  InitializeComponent();
  }

但我已经对此进行了测试,它并没有真正发挥作用。不是应该让程序理解 ok, now you use dot as your decimal separator altough you have values in textBox as "2,5" 之类的东西吗?

ok, now you use dot as your decimal separator altough you have values in textBox as "2,5"

没错。

如果您不使用任何 IFormatProvider

float.TryParse 方法将使用您的 CurrentCulture 设置。

如果您尝试将 "2,5" 解析为没有任何 IFormatProvider 的浮动,您的 CurrentCulture 必须将 , 作为 NumberDecimalSeparator.

如果您尝试将 "2.5" 解析为浮动,您要么使用文化作为另一个已经具有 .作为 NumberDecimalSeparator(如 InvariantCulture), or you can .Clone() your CurrentCulture (as you did) and set it's NumberDecimalSeparator property to . and use this cloned culture as an another parameter in float.TryParse overload.