0
0
Kotlinprogramming~5 mins

String to number conversion in Kotlin

Choose your learning style9 modes available
Introduction
Sometimes, numbers come as text and we need to change them into real numbers to do math or comparisons.
When reading user input that is typed as text but should be a number.
When getting numbers from files or websites where they are stored as text.
When converting form data that is sent as strings but needs to be numbers.
When parsing numbers from text messages or logs.
When you want to check if a string can be a number before using it.
Syntax
Kotlin
val number: Int = string.toInt()
val number: Double = string.toDouble()
val number: Float = string.toFloat()
val number: Long = string.toLong()
Use toInt() for whole numbers, toDouble() for decimal numbers.
If the string is not a valid number, these functions will throw an exception.
Examples
Convert a string with digits to an integer number.
Kotlin
val text = "123"
val num = text.toInt()
Convert a string with decimal digits to a double number.
Kotlin
val text = "45.67"
val num = text.toDouble()
Convert a large number string to a long integer.
Kotlin
val text = "10000000000"
val num = text.toLong()
Convert a string to a floating point number.
Kotlin
val text = "3.14"
val num = text.toFloat()
Sample Program
This program converts two strings into numbers and prints them.
Kotlin
fun main() {
    val intString = "42"
    val doubleString = "3.1415"

    val intNumber = intString.toInt()
    val doubleNumber = doubleString.toDouble()

    println("Integer: $intNumber")
    println("Double: $doubleNumber")
}
OutputSuccess
Important Notes
If the string is not a valid number, use toIntOrNull() or toDoubleOrNull() to avoid errors.
These functions trim leading/trailing whitespace automatically and work if the string represents a valid number with no extra letters or invalid characters.
Although spaces are trimmed automatically, you can use trim() before conversion for other cases if needed.
Summary
Convert strings to numbers to do math or logic with them.
Use toInt(), toDouble(), toFloat(), or toLong() depending on the number type.
Be careful with invalid strings; use safe conversion methods if needed.