Kotlin: check if string is numeric

The method mentioned above will work for a number <= approximately 4*10^18 essentially max limit of Double.

Instead of doing that since String itself is a CharSequence, you can check if all the character belong to a specific range.

val integerChars = '0'..'9'

fun isNumber(input: String): Boolean {
    var dotOccurred = 0
    return input.all { it in integerChars || it == '.' && dotOccurred++ < 1 }
}

fun isInteger(input: String) = input.all { it in integerChars }

fun main() {
    val input = readLine()!!
    println("isNumber: ${isNumber(input)}")
    println("isInteger: ${isInteger(input)}")
}

Examples:

100234
isNumber: true
isInteger: true

235.22
isNumber: true
isInteger: false

102948012120948129049012849102841209849018
isNumber: true
isInteger: true

a
isNumber: false
isInteger: false

Its efficient as well, there's no memory allocations and returns as soon as any non-satisfying condition is found.

You can also include check for negative numbers by just changing the logic if hyphen is first letter you can apply the condition for subSequence(1, length) skipping the first character.


joining all the useful comments and putting it in a input stream context, you can use this for example:

fun readLn() = readLine()!!
fun readNumericOnly() {
    println("Enter a number")
    readLn().toDoubleOrNull()?.let { userInputAsDouble ->
        println("user input as a Double $userInputAsDouble")
        println("user input as an Int ${userInputAsDouble.toInt()}")
    } ?: print("Not a number")


}
readNumericOnly()

for input: 10

user input as a Double 10.0 
user input as an Int 10

for input: 0.1

user input as a Double 0.1 
user input as an Int 0 

for input: "word"

Not a number

Tags:

Kotlin