Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if my string only numeric

Tags:

c#

How I can check if my string only contain numbers?

I don't remember. Something like isnumeric?

like image 868
Gold Avatar asked Dec 24 '10 07:12

Gold


People also ask

How do you check if a string only has letters and numbers?

Use the test() method on the following regular expression to check if a string contains only letters and numbers - /^[A-Za-z0-9]*$/ . The test method will return true if the regular expression is matched in the string and false otherwise.

How do you check if all characters in string are digits?

Python String isnumeric() Method The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values. "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the .

How do I check if a string contains letters?

To check if a string contains any letter, use the test() method with the following regular expression /[a-zA-Z]/ . The test method will return true if the string contains at least one letter and false otherwise. Copied!

How do you check if a string contains only digits in Java?

Using Character.isDigit(char ch). If the character is a digit then return true, else return false.


3 Answers

Just check each character.

bool IsAllDigits(string s) {     foreach (char c in s)     {         if (!char.IsDigit(c))             return false;     }     return true; } 

Or use LINQ.

bool IsAllDigits(string s) => s.All(char.IsDigit); 

If you want to know whether or not a value entered into your program represents a valid integer value (in the range of int), you can use TryParse(). Note that this approach is not the same as checking if the string contains only numbers.

bool IsAllDigits(string s) => int.TryParse(s, out int i); 
like image 82
Jonathan Wood Avatar answered Sep 19 '22 16:09

Jonathan Wood


You could use Regex or int.TryParse.

See also C# Equivalent of VB's IsNumeric()

like image 36
Adriaan Stander Avatar answered Sep 22 '22 16:09

Adriaan Stander


int.TryParse() method will return false for non numeric strings

like image 23
TalentTuner Avatar answered Sep 19 '22 16:09

TalentTuner