按键事件后的十进制数限制 [英] Limit Numbers after Decimal on Key Press Event

查看:95
本文介绍了按键事件后的十进制数限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码仅从用户处获取数字并仅获取一个小数点,这对我在KeyPress Event上正常工作:

I am using the following code to take only digits from user and only one decimal point , that is working fine for me on KeyPress Event :

if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
    e.Handled = true;
}

if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
    e.Handled = true;
}

现在,我想限制小数点后的数字/位数,即35.25468,这意味着它只需要小数点后的6个数字/位数.

Now I want to Limit the numbers/Digits after the decimal/dot i.e 35.25468, means it take only 6 numbers/digits after the dot/decimal.

更新我!

推荐答案

private void price_tb_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 (!char.IsControl(e.KeyChar))
        {

        TextBox textBox = (TextBox)sender;

        if (textBox.Text.IndexOf('.') > -1 &&
                 textBox.Text.Substring(textBox.Text.IndexOf('.')).Length >= 3)
        {
            e.Handled = true;
        }

        }

    }

此代码将为您提供帮助.它只保留小数点后一位和小数点后两位.您可以相应地对其进行更改.

This code will help you. It takes only one decimal place and two digit after one decimal place and you can change it accordingly.

这篇关于按键事件后的十进制数限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆