Only allow two digits after decimal in textbox?

后端 未结 7 919
萌比男神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:30
    string word=txtPrice.Text.Trim();
    string[] wordArr=word.Split('.');
    if(wordArr.Length>1)
    {
       string afterDot=wordArr[1];
       if(afterDot.Length>2)
       {
        alert("Only 2 allowed");
        txtPrice.Text=wordArr[0]+"."+afterDot.SubString(0,2);  
       } 
    }
    
    0 讨论(0)
  • 2020-12-10 19:41

    To address Casperah's comment above you can change the conditional to handle control characters and allow editing if text is selected.

    if (!char.IsControl(e.KeyChar) 
        && Regex.IsMatch(textBox1.Text, @"\.\d\d")
        && String.IsNullOrWhiteSpace(textBox1.SelectedText))
    {
        e.Handled = true;
    }
    
    0 讨论(0)
  • 2020-12-10 19:48

    I believe MaskedTextBox class may help you.

    More info here: https://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox(v=vs.110).aspx

    If it doesn't suit your situation, you can always write yourself a validation and/or a custom control.

    Here's an example of a Numeric TextBox: http://msdn.microsoft.com/en-us/library/ms229644(v=vs.80).aspx#Y0

    0 讨论(0)
  • 2020-12-10 19:50
    namespace WindowsFormsApplication10
    {
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            label1.Text = "";
            double no;
            no = double.Parse(textBox1.Text);
    
            string[] ones = new string[19] {"one ","two ","three ","four ","five ","six ","seven ","eight ","nine ","ten ","eleven ","twele ",
                                            "thiten ","fourten ","fiften ","sixten ","seventeen ","eighteen ", "ninteen "};
            string[] tens = new string[9] { "ten ", "twenty ", "thirty ", "fourty ", "fifty ", "sixty ", "seventy ", "eighty ", "ninty " };
    
            int i=0;
    
    
    
    
            if (no > 999 & no < 100000)
            {
                i = (int)no / 1000;
                if (i < 20)
                    label1.Text = label1.Text + ones[i - 1] + "";
                else if (i > 20)
                {
                    int r = 0;
                    r = i % 10;
                    i = i / 10;
                    label1.Text = label1.Text + tens[i - 1] + "";
                    label1.Text = label1.Text + ones[r - 1] + "";
    
                }
    
                label1.Text = label1.Text + "thousand ";
                no = no % 1000;
            }
    
            if (no > 99 & no < 1000)
            {
                i = (int)no / 100;
                label1.Text = label1.Text + ones[i - 1] + "hundred ";
                no = no % 100;
            }
            if (no > 19 & no < 99)
            {
                i = (int)no / 10;
                label1.Text = label1.Text + tens[i - 1];
                no = no % 10;
            }
            if (no > 0 & no < 20)
            {
                label1.Text = label1.Text + ones[(int)no-1] + " ";
            }
            label1.Text = label1.Text + "Rupees ";
    
    
        }
    
        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            label1.Text = "";
            textBox1.Focus();
    
        }
    
        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;
            }
            string word = textBox1.Text.Trim();
            string[] wordArr = word.Split('.');
            if (wordArr.Length > 1)
            {
                string afterDot = wordArr[1];
                if (afterDot.Length > 1)
                {
    
                    e.Handled = true;
                }
            }
    
        }
    }
    }
    

    here is the program you need.

    0 讨论(0)
  • 2020-12-10 19:53

    Just wanted to point out that the accepted answer will not allow you to enter any numbers BEFORE the decimal point either once that criteria has been met.

    None of the other current examples will work either because they are not getting cursor position

    If you still want to use keypress event you could re-factor your code as follows:

    string senderText = (sender as TextBox).Text;
    string senderName = (sender as TextBox).Name;
    string[] splitByDecimal = senderText.Split('.');
    int cursorPosition = (sender as TextBox).SelectionStart;
    
    if (!char.IsControl(e.KeyChar) 
        && !char.IsDigit(e.KeyChar) 
        && (e.KeyChar != '.'))
    {
        e.Handled = true;
    }
    
    
    if (e.KeyChar == '.' 
        && senderText.IndexOf('.') > -1 )
    {
        e.Handled = true;
    }
    
    
    if (!char.IsControl(e.KeyChar) 
        && senderText.IndexOf('.') < cursorPosition 
        && splitByDecimal.Length > 1 
        && splitByDecimal[1].Length == 2)
    {
        e.Handled = true;
    }
    

    Alternatively, use TextChanged event and do the following and it will work:

    string enteredText = (sender as TextBox).Text;
    int cursorPosition = (sender as TextBox).SelectionStart;
    
    string[] splitByDecimal = enteredText.Split('.');
    
    if(splitByDecimal.Length > 1 && splitByDecimal[1].Length > 2){
        (sender as TextBox).Text = enteredText.Remove(enteredText.Length-1);
        (sender as TextBox).SelectionStart = cursorPosition - 1;
    }
    
    0 讨论(0)
  • 2020-12-10 19:54

    Just add:

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

    to the end of your function

    0 讨论(0)
提交回复
热议问题