In this article you will examine various techniques to find out whether a string is numeric or not in Kotlin.
Method 1: 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") }
Result
-1234.15 is a number
Method 2: 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") }
Result
12345.15 is a number