This article explores different ways to determine whether a given string is a valid number in Kotlin.

1. Using all() function

Kotlin does not offer any standard function to check if the given string is numeric or not. However, this can be efficiently done with the all() function, as shown below:

Download Code

2. Using toInt() function

The trick here is to convert the given string to integer with the toInt() function, which generates NumberFormatException for non-numeric strings. Note that this function fails when the value is outside the integer range.

Download Code

3. Using toIntOrNull() function

Alternatively, you can use the toIntOrNull() function, which parses the string as an Int number and returns the result or null if the string is not a valid representation of a number.

Download Code

4. Using matches() function

Another solution is to use a regular expression to check if a string is numeric or not. We can easily do this with the matches() function, which tells whether this string matches the given regular expression.

Download Code

5. Custom Routine

Finally, you can write your own utility function for this simple task. The basic idea is to iterate over characters of a string and check each character to be numeric.

Download Code

That’s all about checking if a string is a valid number or not in Kotlin.