This article explores different ways to check if a String is numeric in Kotlin.

1. Using toDouble() function

The toDouble() function parses the string as a Double number and returns the result. To determine if the given string is numeric, enclose the toDouble() function call within a try-catch block, and return true if and only if the string is not parsable and no exception is thrown. The following program demonstrates its usage for numerous strings.

Download Code

 
To parse a String as an Int, use the toInt() function:

Download Code

2. Using NumberFormat.parse() function

Another option is to use the NumberFormat.parse() function to parse a string. If the object can’t be parsed, it does not throw an exception, but the index remains unchanged. A typical implementation of this function would look like this:

Download Code

3. Using allMatch() function

To check if the string is just a sequence of digits, use the allMatch() function. The following solution demonstrates this using the Character.isDigit() function.

Download Code

That’s all about checking if a String is numeric in Kotlin.