Determine if a string is a valid number or not in Kotlin
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:
|
1 2 3 4 5 6 7 8 |
fun isNumber(s: String?): Boolean { return if (s.isNullOrEmpty()) false else s.all { Character.isDigit(it) } } fun main() { val s = "100" if (isNumber(s)) print("Number") else print("Not a Number") // Number } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun isNumber(s: String): Boolean { return try { s.toInt() true } catch (ex: NumberFormatException) { false } } fun main() { val s = "100" if (isNumber(s)) print("Number") else print("Not a Number") // Number } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun isNumber(s: String): Boolean { return when(s.toIntOrNull()) { null -> false else -> true } } fun main() { val s = "100" if (isNumber(s)) print("Number") else print("Not a Number") // Number } |
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.
|
1 2 3 4 5 6 7 8 |
fun isNumber(s: String?): Boolean { return !s.isNullOrEmpty() && s.matches(Regex("\\d+")) } fun main() { val s = "100" if (isNumber(s)) print("Number") else print("Not a Number") // Number } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
fun isNumber(s: String?): Boolean { if (s == null || s.length == 0) { return false } for (c in s) { if (c < '0' || c > '9') { return false } } return true } fun main() { val s = "100" if (isNumber(s)) print("Number") else print("Not a Number") // Number } |
That’s all about checking if a string is a valid number or not in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)