Reputation: 829
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
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
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