Как проверить является ли строка числом c
Перейти к содержимому

Как проверить является ли строка числом c

  • автор:

Как проверить, является ли строка числом в C#

Проверка, является ли строка числом или нет в C# #

Например, у нас есть строковая переменная “123”, и если вы хотите проверить, является ли она числовой, используйте приведенный ниже код на C#.

Начиная с C# 7 мы можем объявить переменную out в самом методе TryParse.

Проблема с приведенным выше методом int.TryParse заключается в том, что он не может проверить отрицательные значения строковых чисел.

Проверка отрицательного числа строк в C# #

Для проверки отрицательных значений числа строк мы можем использовать метод C# double.TryParse() .

Лучший способ проверить, является ли строка числом в C# #

Для проверки того, является ли строка числом, всегда используйте метод double.TryParse() , поскольку он может проверять как положительные, так и отрицательные числа.

Don’t be a Stranger. Connect me at Social Networking Sites.

�� Stay in the loop

Get a short & sweet tutorials delivered to your inbox every couple of days. No spam ever. Unsubscribe any time.

Check If String Is A Number In C#

Check If String Is A Number In C#

In this blog post, we will learn how to check if a string is a proper number or integer in C#.

Let’s say you have a code in which you are getting a age as a string from a database call and you want to check if this string is a number or not before you could use it, this is where this check would be handy.

Check If String Is A Number In C# Using int.Parse() Method

In this method, we will use the int.Parse() method and check if the string is a number or not.

The int.Parse() method takes a string as a parameter and then outputs the integer value if the string is a valid number.

If the string is not a valid number or integer, the method throws the exception telling us that this string is not a number.

Let’s see this in an example.

In the above code example, we can see that we want to check if the value in the string is a valid number or not.

We are using the int.Parse() method to get the int output and writing that to the console.

Let’s see another example in which the string was not a valid number.

Check If String Is A Number In C# Using int.TryParse() Method

In this method, we will use the int.TryParse() method and check if the string is a number or not.

This method takes in the string as a parameter and gives an out parameter of an integer.

If the string to int conversion was successful, it populates the out parameter with the number value and returns a boolean of true, sugesting that the conversion was sussessful.

If the conversion failed because the string was not a valid number, then the int.TryParse() method returns a boolean of false and the out parameter value as the default integer value, i.e. 0.

Let’s see this in an example.

String is a valid number. The value is 55

If this was string was not a valid number then unlike the Parse method, we would gracefully be able to handle the result and make a decision.

How to check if a character is a digit in C#

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

Overview

A character can be an alphabet, symbol, etc. In other words, a character can be alphanumeric. In C#, we can use the IsDigit() method to check if a character is numeric or a digit.

The IsDigit() method can be used on a single character or on a string. In the case of a string, we have to specify the index position of the character in the string.

IsDigit() returns true if the character is a decimal digit; otherwise, it returns false .

Syntax
Parameters

Char : The character we want to check.

String : The string that we want to check to see if any character at index position int32 is a digit.

int32 : The index position of the character in a string we want to check.

Code example

In the example below, we create some strings and characters and see if certain characters are decimal digits or not.

Identify if a string is a number

Is there a command, like IsNumeric() or something else, that can identify if a string is a valid number?

26 Answers 26

Update As of C# 7:

or if you don’t need the number you can discard the out parameter

The var s can be replaced by their respective types!

Vadim Ovchinnikov's user avatar

mqp's user avatar

This will return true if input is all numbers. Don’t know if it’s any better than TryParse , but it will work.

If you just want to know if it has one or more numbers mixed in with characters, leave off the ^ + and $ .

Edit: Actually I think it is better than TryParse because a very long string could potentially overflow TryParse.

You can also use:

It will return true for all Numeric Digits (not float ) and false if input string is any sort of alphanumeric.

Test case Return value Test result
"1234" true ✅Pass
"1" true ✅Pass
"0" true ✅Pass
"" true ⚠️Fail (known edge case)
"12.34" false ✅Pass
"+1234" false ✅Pass
"-13" false ✅Pass
"3E14" false ✅Pass
"0x10" false ✅Pass

Please note: stringTest should not be an empty string as this would pass the test of being numeric.

I’ve used this function several times:

But you can also use;

Glorfindel's user avatar

This is probably the best option in C#.

If you want to know if the string contains a whole number (integer):

The TryParse method will try to convert the string to a number (integer) and if it succeeds it will return true and place the corresponding number in myInt. If it can’t, it returns false.

Solutions using the int.Parse(someString) alternative shown in other responses works, but it is much slower because throwing exceptions is very expensive. TryParse(. ) was added to the C# language in version 2, and until then you didn’t have a choice. Now you do: you should therefore avoid the Parse() alternative.

If you want to accept decimal numbers, the decimal class also has a .TryParse(. ) method. Replace int with decimal in the above discussion, and the same principles apply.

You can always use the built in TryParse methods for many datatypes to see if the string in question will pass.

Result would then = True

Result would then = False

Trevor Tubbs's user avatar

In case you don’t want to use int.Parse or double.Parse, you can roll your own with something like this:

If you want to catch a broader spectrum of numbers, à la PHP’s is_numeric, you can use the following:

Keep in mind that just because a value is numeric doesn’t mean it can be converted to a numeric type. For example, «999999999999999999999999999999.9999999999» is a perfeclty valid numeric value, but it won’t fit into a .NET numeric type (not one defined in the standard library, that is).

JDB's user avatar

I know this is an old thread, but none of the answers really did it for me — either inefficient, or not encapsulated for easy reuse. I also wanted to ensure it returned false if the string was empty or null. TryParse returns true in this case (an empty string does not cause an error when parsing as a number). So, here’s my string extension method:

Or, if you want to test other types of number, you can specify the ‘style’. So, to convert a number with an Exponent, you could use:

Or to test a potential Hex string, you could use:

The optional ‘culture’ parameter can be used in much the same way.

It is limited by not being able to convert strings that are too big to be contained in a double, but that is a limited requirement and I think if you are working with numbers larger than this, then you’ll probably need additional specialised number handling functions anyway.

cyberspy's user avatar

UPDATE of Kunal Noel Answer

But, for this case we have that empty strings will pass that test, so, you can:

You can use TryParse to determine if the string can be parsed into an integer.

The boolean will tell you if it worked or not.

If you want to know if a string is a number, you could always try parsing it:

Note that TryParse returns a bool , which you can use to check if your parsing succeeded.

I guess this answer will just be lost in between all the other ones, but anyway, here goes.

I ended up on this question via Google because I wanted to check if a string was numeric so that I could just use double.Parse(«123») instead of the TryParse() method.

Why? Because it’s annoying to have to declare an out variable and check the result of TryParse() before you know if the parse failed or not. I want to use the ternary operator to check if the string is numerical and then just parse it in the first ternary expression or provide a default value in the second ternary expression.

It’s just a lot cleaner than:

I made a couple extension methods for these cases:

Extension method one

Example:

Because IsParseableAs() tries to parse the string as the appropriate type instead of just checking if the string is «numeric» it should be pretty safe. And you can even use it for non numeric types that have a TryParse() method, like DateTime .

The method uses reflection and you end up calling the TryParse() method twice which, of course, isn’t as efficient, but not everything has to be fully optimized, sometimes convenience is just more important.

This method can also be used to easily parse a list of numeric strings into a list of double or some other type with a default value without having to catch any exceptions:

Extension method two

This extension method lets you parse a string as any type that has a TryParse() method and it also lets you specify a default value to return if the conversion fails.

This is better than using the ternary operator with the extension method above as it only does the conversion once. It still uses reflection though.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *