Kotlin Program to Check if a String is Numeric

Example 1: Check if a string is numeric

import java.lang.Double.parseDouble

fun main(args: Array<String>) {

    val string = "12345s15"
    var numeric = true

    try {
        val num = parseDouble(string)
    } catch (e: NumberFormatException) {
        numeric = false
    }

    if (numeric)
        println("$string is a number")
    else
        println("$string is not a number")
}

When you run the program, the output will be:

12345s15 is not a number

In the above program, we have a String named string which contains the string to be checked. We also have a boolean value numeric which stores if the final result is numeric or not.

To check if string contains numbers only, in the try block, we use Double's parseDouble() method to convert the string to a Double.

If it throws an error (i.e. NumberFormatException error), it means string isn't a number and numeric is set to false. Else, it's a number.

However, if you want to check if, for a number of strings, you would need to change it to a function. And, the logic is based on throwing exceptions, this can be pretty expensive.

Instead, we can use the power of regular expressions to check if the string is numeric or not as shown below.


Example 2: Check if a string is numeric or not using regular expressions (regex)

fun main(args: Array<String>) {

    val string = "-1234.15"
    var numeric = true

    numeric = string.matches("-?\\d+(\\.\\d+)?".toRegex())

    if (numeric)
        println("$string is a number")
    else
        println("$string is not a number")
}

When you run the program, the output will be:

-1234.15 is a number

In the above program, instead of using a try-catch block, we use regex to check if string is numeric or not. This is done using String's matches() method.

In the matches() method,

  • -? allows zero or more - for negative numbers in the string.
  • \\d+ checks the string must have at least 1 or more numbers (\\d).
  • (\\.\\d+)? allows zero or more of the given pattern (\\.\\d+) in which
    • \\. checks if the string contains . (decimal points) or not
    • If yes, it should be followed by at least one or more number \\d+.

Here's the equivalent Java code: Java program to check if a string is numeric or not.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges