String.toInt() / toDouble()
Extension functions for converting strings to numeric types and numbers to strings. They also provide safe handling when conversion fails.
Syntax
// Converts a string to an integer. Throws NumberFormatException if conversion fails. string.toInt() string.toInt(radix: Int) // Converts using the specified radix // Safe version that returns null if conversion fails. string.toIntOrNull() // Converts a number to a string. number.toString() number.toString(radix: Int) // Converts to a string using the specified radix
Method List
| Method | Description |
|---|---|
| toInt() | Converts a string to an Int. Throws NumberFormatException if conversion fails. |
| toIntOrNull() | Converts a string to an Int, or returns null if conversion fails. |
| toLong() / toLongOrNull() | Converts a string to a Long. |
| toDouble() / toDoubleOrNull() | Converts a string to a Double. |
| toFloat() / toFloatOrNull() | Converts a string to a Float. |
| toBooleanStrict() | Converts a string to a Boolean. Throws an exception for any value other than "true" or "false". |
| toString() | Converts any object to a string. For numbers, you can optionally specify a radix. |
Sample Code
fun main() {
// Convert a string to an integer.
val numStr = "42"
val num = numStr.toInt()
println(num + 8) // 50
// Returns null if conversion fails.
val invalid = "abc"
val result = invalid.toIntOrNull()
println(result) // null
// Use the Elvis operator to provide a default value.
val value = "xyz".toIntOrNull() ?: 0
println(value) // 0
// Convert to a floating-point number.
val pi = "3.14159"
println(pi.toDouble()) // 3.14159
// Convert a hexadecimal string to an integer.
val hex = "ff"
println(hex.toInt(radix = 16)) // 255
// Convert a number to a string.
val n = 255
println(n.toString()) // 255
println(n.toString(radix = 2)) // 11111111 (binary)
println(n.toString(radix = 16)) // ff (hexadecimal)
// Numbers are also converted automatically inside string templates.
val score = 98
println("Your score is ${score} points.")
}
Notes
Conversion functions such as toInt() throw a NumberFormatException if the string is not in the expected format. When handling user input or external data, always use the safe variants such as toIntOrNull() and check for null.
toString() is a method available on every Kotlin object. When called on a number, you can specify a radix (2–36) to convert it to binary, octal, hexadecimal, or any other base. Inside a string template (${}), toString() is called automatically.
If you find any errors or copyright issues, please contact us.