Joshua Hansen
12/08/2025, 9:16 PMval myString = "1234"
val isNumeric = myString.toIntOrNull() != null
val isNumeric2 = myString.all { it.isDigit() }hho
12/08/2025, 10:00 PMJoshua Hansen
12/08/2025, 10:42 PMephemient
12/09/2025, 10:30 AM"".all { it.isDigit() } == true, and you probably shouldn't consider that an integerephemient
12/09/2025, 10:30 AM"09" has some varying interpretationsStephan Schröder
12/09/2025, 3:14 PMfun String.isInteger(): Boolean {
if(this.isEmpty()) return false
val firstDigitIndex = if(this[0] == '-') {
if(this.length==1) return false
1
} else 0
if(this[firstDigitIndex]=='0') return false
return this.substring(firstDigitIndex).all {it.isDigit()}
}
• disallows "", "-", "0...", "-0..."
• doesn't check for Int.MAX/MIN_VALUE
• should work as requested otherwise
val isNumeric = myString.toIntOrNull() != null
looks suddenly very tempting, if and only if you want to make sure that this integer fits inside of an Int.ephemient
12/09/2025, 3:23 PM"0".isInteger() == false doesn't look intendedStephan Schröder
12/09/2025, 3:27 PMfun String.isInteger(): Boolean = when {
this.isEmpty() -> false
this == "0" -> true
this == "-0" -> true
else -> {
val firstDigitIndex = if(this[0] == '-') {
if(this.length==1) return false
1
} else 0
this[firstDigitIndex] != '0' && this.substring(firstDigitIndex).all { it.isDigit() }
}
}ephemient
12/09/2025, 3:27 PM"-0" is debatable but Java and Kotlin allow it 😛Stephan Schröder
12/09/2025, 3:28 PMephemient
12/09/2025, 3:28 PM.toIntOrNull() != null is the most straightforward solution if you are looking for Int-sized integersephemient
12/09/2025, 3:28 PMStephan Schröder
12/09/2025, 3:28 PMStephan Schröder
12/09/2025, 3:29 PMephemient
12/09/2025, 3:29 PM"""-?(?:0|[1-9][0-9]*)""".toRegex()Stephan Schröder
12/09/2025, 3:29 PMStephan Schröder
12/09/2025, 3:30 PMStephan Schröder
12/09/2025, 3:33 PMprivate val integerRegex = """-?(?:0|[1-9][0-9]*)""".toRegex()
fun String.isInteger(): Boolean = integerRegex.matches(this)