1

In Windows forms C#, I want to check if a textbox I made starts with a numeric value, then if it does I want to insert the minus (-) sign at the beginning to change the number to negative, I found a way but it's too time wasting, here's my code:

if (richTextBox1.Text.StartsWith("1") || richTextBox1.Text.StartsWith("2") #until richTextBox1.Text.StartsWith("9")) { richTextBox1.Text.Insert(0, "-"); } 

So I was asking, if there's a shorter way to replace that code?

4 Answers 4

5
if (Char.IsNumber(richTextBox1.Text[0]))... 

You should also add some checks around it to make sure there's text.

Sign up to request clarification or add additional context in comments.

2 Comments

Is this cultural specific?
@Çöđěxěŕ It "Indicates whether a Unicode character is categorized as a number". Also, check the remarks section for more info.
0

Using regex:

if (Regex.IsMatch(richTextBox1.Text, @"^\d")) 

Matches a digit (0-9) at the start of the string.

Or a direct replace:

richTextBox1.Text = Regex.Replace(richTextBox1.Text, @"^\d", "-$&"); 

Comments

0

Checking if the first character of a text is a number can be done in single line, using Char.IsNumber() function as follows:

if ( Char.IsNumber( stringInput, 0) ) {

 // String input begins with a number 

}

More information: https://learn.microsoft.com/en-us/dotnet/api/system.char.isnumber

Comments

-1

Many good answer's already here, another alternative is if you want culture support give this a try...

 public static bool IsNumber(char character) { try { int.Parse(character.ToString(), CultureInfo.CurrentCulture); return true; } catch (FormatException) { return false; } } 

You can call it like:

 if ( IsNumber(richTextBox1.Text[0])) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.