Only allow two digits after decimal in textbox?

后端 未结 7 920
萌比男神i
萌比男神i 2020-12-10 18:54

I have a textbox where the user enters a number, but how can i make it so that if they type the \'.\' after it it only allows 2 decimal places?

private void          


        
相关标签:
7条回答
  • 2020-12-10 19:54

    Personaly I am using this, Its not very elegant but works like a charm. This script restrict user to use only numeric characters, only 1 dot ,just 2 decimal numbers and backspace.

    so acceptable inputs will be something like : 1.22 , 2135.25, 3535.5 etc.

    void Decimal(object sender, KeyPressEventArgs Event) {
                Event.Handled = true;
                bool FalseInput = !char.IsControl(Event.KeyChar) && !char.IsDigit(Event.KeyChar) && !char.IsControl(Event.KeyChar) && Event.KeyChar != 8 && Event.KeyChar != '.';
                if (!FalseInput){
                    Event.Handled = false;
                    if (Regex.IsMatch(FreightTextBox.Text, @"^\d+\.\d*$") && Event.KeyChar != 8) {
                        bool ContainDot = FreightTextBox.Text.Contains(".");
                        Event.Handled = true;
                        if (ContainDot && Event.KeyChar != 8 && Event.KeyChar!='.'){
                            Event.Handled = Regex.IsMatch(FreightTextBox.Text, @"\.\d\d");
                        }
                    }
                }
            }
    
    0 讨论(0)
提交回复
热议问题