Introduction
Sometimes, numbers come as text and we need to change them into real numbers to do math or comparisons.
val number: Int = string.toInt() val number: Double = string.toDouble() val number: Float = string.toFloat() val number: Long = string.toLong()
toInt() for whole numbers, toDouble() for decimal numbers.val text = "123" val num = text.toInt()
val text = "45.67" val num = text.toDouble()
val text = "10000000000" val num = text.toLong()
val text = "3.14" val num = text.toFloat()
fun main() { val intString = "42" val doubleString = "3.1415" val intNumber = intString.toInt() val doubleNumber = doubleString.toDouble() println("Integer: $intNumber") println("Double: $doubleNumber") }
toIntOrNull() or toDoubleOrNull() to avoid errors.trim() before conversion for other cases if needed.toInt(), toDouble(), toFloat(), or toLong() depending on the number type.String to an Int?toInt() to convert strings to integers, toDouble() for doubles, and toString() converts other types to strings.String to an Int, toInt() is the correct function."123" to an integer?toInt() on the string object, like "123".toInt().toInteger().val s = "45" val n = s.toInt() + 10 println(n)
toInt(). Then 10 is added, resulting in 55.println(n) outputs the integer 55, not string concatenation.val s = "abc" val n = s.toInt() println(n)
toInt() on a string that is not a valid number throws a NumberFormatException at runtime.listOf("10", "20", "abc", "30"). Which Kotlin code safely converts valid strings to integers and ignores invalid ones?toIntOrNull() returns null if conversion fails, avoiding exceptions.mapNotNull { it.toIntOrNull() } converts valid strings and removes nulls from invalid ones.Pass the test and this pattern moves unknown