简体   繁体   中英

How can I restrict the input of decimals points to only 1 in C#?

The code below restricts everything I need restricted, but it allows the user to input more than 1 decimal point

if (System.Text.RegularExpressions.Regex.IsMatch(txtOperand2.Text, 
    "[^0-9],[.],[\b]"))  
{
       MessageBox.Show("Please enter only numbers."); 
       txtOperand2.Text = txtOperand2.Text.Remove(txtOperand2.Text.Length - 1);
}

As per @DourHighArch 's worthy comment. If you are just checking for a valid decimal to a certain number of places, and you want a fast culture aware solution (and other configurability like number styles ).

Instead of regex, you could do something like this. decimal.TryParse and checking how many decimal places it has via some means.

Converts the string representation of a number to its Decimal equivalent. A return value indicates whether the conversion succeeded or failed.

Given

// gets the decimal places by deconstruction
public static int GetDecimalPlaces(decimal d)
   => BitConverter.GetBytes(decimal.GetBits(d)[3])[2];

Usage

if (decimal.TryParse(argument, out var d) && GetDecimalPlaces(d) == 1)
    Console.WriteLine("You win, play again?");

Add pepper and salt to taste

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM