带小数的文本框格式

时间:2016-07-28 17:03:43

标签: c# winforms decimal

我在winform中有一个textBox,用于计算Money值。

我想要的行为是:

加载时:

0,00

如果我写的东西应该从右到左替换......

所以,如果我要显示100

我应输入1 0 0 0 0

为了textBox逐步显示:

0,01 
0,10 
1,00 
10,00 
100,00 

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

这是我的解决方案。这不支持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,否则文本框将为空

答案 1 :(得分:0)

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

s.trim.split(' ').map(_.toDouble)

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

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);
}