In many programming scenarios, determining whether the string represents the ability to represent numbers is very important. String such as "123" should be identified as numbers, while string such as "ABC" or "AB2" should not be recognized as numbers.
Isnumeric () function
In C#, there is no clear isnumeric ()
function to check whether the string is numbers. However, the TryParse () method in the int class can effectively achieve this goal.
Try to convert the string to an integer. If the conversion is successful, it returns True, indicating that the string is an effective number. Otherwise, return false. Example is as follows:
In this code, TryParse ()
Try to analyze the string "123" as an integer. If it is successful, the value of nwill be set to 123, and
isnumeric1 2 |
|
<> C# 7 and the higher version update In C# 7 and higher versions, you can omit OUT Parameter:
or, if there is no need to analyze the value:
<:> Note: Here VAR
The keywords can be replaced with a specific data type, such as1 |
|
.
The above is the detailed content of How Can I Check if a String Represents a Number in C#?. For more information, please follow other related articles on the PHP Chinese website!