aco
aco

Reputation: 829

Allow input only 2 decimals (C# + WindowsPhone)

I am using this code to allow only input 1 decimal point. It runs fine. But how I can do it to allow input only 2 numbers after decimal point?

C#

 private void txtPrecio_KeyDown(object sender, KeyEventArgs e)
    {
        TextBox txt1 = (TextBox)sender;

        if (txt1.Text.Contains(".") && e.PlatformKeyCode == 190)
        {
            e.Handled = true;
        }           
    }

Upvotes: 0

Views: 1379

Answers (3)

Rising Force
Rising Force

Reputation: 13

Why not just format the result:

double e = double.Parse(text);
string nText = string.Format("{0:0.##}", e);
e = double.Parse(nText);

Upvotes: 1

Matt Lacey
Matt Lacey

Reputation: 65564

Just check if the last character is a numeric value, the penultimate character is a numeric value and the character before that is a dot/period.

Or if you wanted to ue a Regex*, something like

if (Regex.IsMatch(".[0-9]{2}$", txt1.Text)
{
    e.Handled = true;
}

*-This regex was done from memory but it's looking (intended to) to see if the text endswith a decimal place and then 2 numeric characters.

Upvotes: 1

Ani
Ani

Reputation: 10896

Perhaps this or some other Silverlight based masked edit could help you solve your problem in a much cleaner fashion?

Hope this helps.

Upvotes: 2

Related Questions