“.”前只有一个“0”在 textBox_TextChanged

Only one "0" before "." in textBox_TextChanged

如何在“.”前只留一个“0”?我正在制作 TextBox,它只接受数字,你只能在“.”之前写一个“0”,但你可以写任何数字,如 900 或 5000。

这是我使用的伪代码:

if (0 > 1 before "." && 0 is first digit) 
{
    Remove all zeros before "." and left one; 
}

像这样使用它

for (int i=0;i<textbox.Text.Length;i++)
{
    textbox.Text=textbox.Text.Replace("00.","0.")
}

最简单的方法可能是删除开头的所有 0;

textbox.Text = textbox.Text.TrimStart('0');

然后如果它以“.”开头再次在开头添加一个“0”。

if (textbox.Text.StartsWith('.'))
    textbox.Text = '0' + textbox.Text;

这也会删除开头的任何 0,例如“00500”,将其更改为“500”,这可能是一件好事。

中继 TextChanged 事件有一些缺点。例如,用户可能希望输入零,然后在它们前面加上数字 (.) 符号。在输入数字之前,您的代码将删除所有前导零。最好使用其他事件,如 Validating 或 LostFocus。代码会很简单:

textbox.Text = textbox.Text.TrimStart('0');

您可以使用 NumericUpDown 控件进行纯数字输入。它将验证文本是否为数字并根据 DecimalPlaces 等设置对其进行格式化。

也许这个可以帮助:

public string ZeroPoint(string a)
{
  int pos = a.IndexOf(".");
  if (pos > -1 && a.Substring(0, pos) == new string('0', pos))
  {
    a = "0" + a.Substring(pos, a.Length - pos);
  }
  return a;
}

您需要使用 KeyPress 事件并添加以下逻辑来确定按下的是什么以及输入的值将放置在何处。

当您将 e.Handled 值设置为 true 时,您就是在告诉系统忽略用户输入。

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    // Only allow digits, decimal points and control characters (Backspace, delete, etc)
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
        (e.KeyChar != '.'))
    {
        e.Handled = true;
    }

    int PointIndex = (sender as TextBox).Text.IndexOf('.');

    // only allow one decimal point and one digit before decimal point
    if (((e.KeyChar == '.') && PointIndex > -1) || 
        (e.KeyChar == '.' && textBox1.SelectionStart > 1) ||
        (PointIndex == 1 && textBox1.SelectionStart <= PointIndex))
    {
        e.Handled = true;
    }
}

此代码在用户输入时验证用户输入。

编辑:

此外,由于此代码仅在用户输入时验证输入,因此您还需要防止他们粘贴无效值。您可以通过将文本框的 ShortcutsEnabled 属性 设置为 false 来实现。