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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9967558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 11:25:29  来源:igfitidea点击:

Only allow two digits after decimal in textbox?

c#winforms

提问by user710502

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

采纳答案by aquinas

Just add:

只需添加:

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

to the end of your function

到你的函数结束

回答by Shyju

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

回答by walther

I believe MaskedTextBox class may help you.

我相信 MaskedTextBox 类可以帮助你。

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

更多信息: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

下面是一个数字文本框的例子:http: //msdn.microsoft.com/en-us/library/ms229644(v=vs.80) .aspx#Y0

回答by pradeep

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.

这是您需要的程序。

回答by Scott

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:

如果您仍然想使用 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;
}

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

或者,使用 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;
}

回答by dramatix01

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

要解决上面 Casperah 的评论,您可以更改条件以处理控制字符并允许在选择文本时进行编辑。

if (!char.IsControl(e.KeyChar) 
    && Regex.IsMatch(textBox1.Text, @"\.\d\d")
    && String.IsNullOrWhiteSpace(textBox1.SelectedText))
{
    e.Handled = true;
}

回答by Philip Valvis

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.

我个人正在使用这个,它不是很优雅,但就像一个魅力。这个脚本限制用户只能使用数字字符,只有 1 个点,只有 2 个十进制数字和退格。

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

所以可接受的输入将类似于: 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");
                    }
                }
            }
        }