带小数的文本框格式

本文关键字:格式 文本 小数 | 更新日期: 2023-09-27 17:59:10

我有一个winform中的textBox,它将用于计算Money值。

我想要的行为是这样的:

加载:

0,00

如果我写一些东西,它应该从右到左替换。。。

所以,如果我想显示100

我应该键入1 0 0 0 0

为了使文本框逐渐显示:

0,010,101,0010,00100000

我怎样才能做到这一点?

带小数的文本框格式

这是我的解决方案。这不支持numPad输入,你想要吗?

string valueText = ""; // The sequence of numbers you've entered. Ex. 1 0 0 0 0
// This ensures that the textbox allways shows something like "0,00"
private void textBox1_TextChanged(object sender, EventArgs e)
{
    string inputText = ""; // The text to print in textbox
    if (valueText.Length < 3) // If there are under 3 numbers in the number you've entered, add zeros before the number. Ex. if you've entered: 1 0 , then the box should print "0,10". Therefore, add the zeros if the value text's length is below 3
    {
        for (int zeros = 0; zeros < 3 - valueText.Length; zeros++)
            inputText += "0";
    }
    inputText += valueText; // Append the numbers you've entered
    textBox1.Text = inputText.Insert(inputText.Length - 2, ","); // insert the comma two positions from the right end
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    List<Keys> keys = new List<Keys>() { Keys.D1, Keys.D2, Keys.D3, Keys.D4, Keys.D5, Keys.D6, Keys.D7, Keys.D8, Keys.D9, Keys.D0 }; // The keys you can press to enter a number
    if (keys.Contains(e.KeyCode)) // If the key you pressed is "accepted"
    {
        valueText += e.KeyCode.ToString().Replace("D", ""); // the key "1" will be "D1", therefore, remove the "D"
    }
    else if (e.KeyCode == Keys.Back) // If backspace is pressed
    {
        if (valueText.Length > 0)
            valueText = valueText.Remove(valueText.Length - 1, 1); // Remove the last number Ex. 1,00 + backspace = 0,10
    }
    textBox1_TextChanged(null, EventArgs.Empty); // Update the text in the textBox
}

我希望这能有所帮助。

编辑:记得在启动时调用textBox1_TextChanged,否则文本框将为空

创建一个事件处理程序,拦截文本输入并根据需要格式化:

private void textBox_TextChanged(object sender, EventArgs e)
{
    double value = 0;
    if(double.TryParse(textBox.Text, out value))
        value /= 100.0;
    textBox.Text = String.Format("{0:f2}", value);
}

您可能还需要限制用户可以在文本框中插入的字符:

protected override void OnKeyPress(KeyPressEventArgs e)
{
    base.OnKeyPress(e);
    // let digits and . go
    if(char.IsDigit(e.KeyChar) || (e.KeyChar == '.'))
        return;
    // all other chars are ignored,
    // you can add other stuff here if needed like
    // the minus sign, backspace etc
    e.Handled = true;
}