English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn different techniques to check if a string is a number in Kotlin.
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 running the program, the output is:
12345s15 is not a number
In the above program, we have a string named string that contains the string to be checked. We also have a boolean value numeric to store the final result whether it is a number or not.
To check if string contains only numbers, in the try block, we use the Double.parseDouble() method to convert the string to Double.
If an error is thrown (i.e., NumberFormatException error), it means that string is not a number, and set numeric to false. Otherwise, it is a number.
However, if you need to check a certain number of strings, you need to change it to a function. And, the logic is based on throwing exceptions, which can be very costly.
On the contrary, we can use the features of regular expressions to check if a string is a number, as shown below.
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 running the program, the output is:
-1234.15 It is a number
In the above program, we use regex to check if the string is a number, rather than using try-catch block. This is done using the String's matches() method.
in the catch block. This is done using the String's matches() method.
-? Allows zero or more-negative numbers in the string.
\\d+ Check that the string must contain at least1one or more numbers (\\d).
(\\.\\d+)? Allows zero or more of the given pattern (\\.\\d+) among them
\\..Check if the string contains a period (decimal point)
If so, it should at least match one or more numbers \\d+.
This is the equivalent Java code:Java Program to Check If a String Is a Number.