Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: check if string is numeric

Tags:

kotlin

Is there a simple way to check if user's input is numeric? Using regexes and exceptions seems too complicated here.

fun main {
    val scan = Scanner(System.`in`)
    val input = scanner.nextLine()
    if (!input.isNumeric) {
        println("You should enter a number!")
    }
}
like image 609
antomatskev Avatar asked Dec 28 '20 08:12

antomatskev


2 Answers

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.

like image 178
Animesh Sahu Avatar answered Sep 24 '22 16:09

Animesh Sahu


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
like image 42
Ben Shmuel Avatar answered Sep 21 '22 16:09

Ben Shmuel