簡體   English   中英

文本框中只允許小數點后兩位?

[英]Only allow two digits after decimal in textbox?

我有一個文本框,用戶可以在其中輸入一個數字,但是如果他們鍵入“。”,我該如何做到這一點? 在它之后它只允許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; 
    } 
}

只需添加:

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

到你的功能結束

只是想指出,一旦滿足該標准,接受的答案將不允許您在小數點之前輸入任何數字。

當前的其他示例都不起作用,因為它們沒有獲得光標位置

如果您仍想使用 keypress 事件,您可以按如下方式重構您的代碼:

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

或者,使用 TextChanged 事件並執行以下操作,它將起作用:

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

    }
}
}

這是您需要的程序。

我個人正在使用它,它不是很優雅,但就像一個魅力。 這個腳本限制用戶只能使用數字字符,只有 1 個點,只有 2 個十進制數字和退格。

所以可接受的輸入將類似於:1.22、2135.25、3535.5 等。

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");
                    }
                }
            }
        }
<asp:TextBox ID="txtTotalMarks" ClientIDMode="Static" runat="server" onkeypress="return isNumberKey(event,this)"></asp:TextBox>
function isNumberKey(evt, element) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8))
        return false;
    else {
        var len = $(element).val().length;
        var index = $(element).val().indexOf('.');
        if (index > 0 && charCode == 46) {
            return false;
        }
        if (index > 0) {
            var CharAfterdot = (len + 1) - index;
            if (CharAfterdot > 3) {
                return false;
            }
        }

    }
    return true;
}

我相信 MaskedTextBox 類可以幫助你。

更多信息: https ://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox(v=vs.110).aspx

如果它不適合您的情況,您可以隨時為自己編寫驗證和/或自定義控件。

這是一個數字文本框的示例:http: //msdn.microsoft.com/en-us/library/ms229644 (v=vs.80).aspx#Y0

我有一個文本框,用戶可以在其中輸入數字,但是如果他們鍵入“。”,我該如何輸入呢? 之后它只允許小數點后兩位?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM