文本框中只允许小数后两位数?

use*_*502 5 c# winforms

我有一个文本框,用户输入一个数字,但我怎么能这样做,如果他们输入'.' 之后它只允许2位小数?

private void textBox1_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if (!char.IsControl(e.KeyChar)  
        && !char.IsDigit(e.KeyChar)  
        && e.KeyChar != '.') 
    { 
        e.Handled = true; 
    } 

    // only allow one decimal point 
    if (e.KeyChar == '.'  
        && (sender as TextBox).Text.IndexOf('.') > -1) 
    { 
        e.Handled = true; 
    } 
}
Run Code Online (Sandbox Code Playgroud)

aqu*_*nas 10

只需添加:

if (Regex.IsMatch(textBox1.Text, @"\.\d\d")) {
   e.Handled = true;
}
Run Code Online (Sandbox Code Playgroud)

到你的功能结束

  • `if(Regex.IsMatch(txtPartsNOthers.Text,@"\.\ d\d")&& e.KeyChar!= 8){e.Handled = true;}`只需替换为this.Because Backspace键在两个之后不能工作小数点填满.当你想改变小数值时,你不能使用上面的RegEx而不添加`&& e.KeyChar!= 8` (4认同)