МагазинНовостиПравилаПомощьДокументацияПрисоединиться

Type conversion

Conversion between numeric types

In practice, you will usually use three numeric types: Int, Long, and Double. Sometimes, you may need to assign the value of one numeric type to a variable of another numeric type. To do that, you must perform a type conversion by invoking a special function such as toInt(), toLong(), toDouble(), and so on.

Imagine you have a variable called num of the Int type, and you want to pass it to a function called sqrt, that finds the square root of a number. This function takes Double rather than Int, so you should convert the value using toDouble() to prevent a type mismatch error.

val num: Int = 100

val res: Double = Math.sqrt(num.toDouble())
println(res) // 10.0

println(num) // 100, it is not modified

In this example, types for variables are specified to simplify the explanation.

Note that toDouble() does not modify the type of num, it is impossible. This function produces a new value of Double type.

You can perform such operations even when the target type is larger (e.g., Long, 64 bits) than the source type (e.g., Int, 32 bits). This greatly distinguishes Kotlin from other programming languages like Java and C#, in which a number of a smaller type can be assigned to a variable of a larger type without additional actions.

val num: Int = 100
val bigNum: Long = num.toLong() // 100

Despite the fact that Char is not a numeric type, you can convert a number to a character and vice versa according to the character code (which can be found in the Unicode table). This code can be considered as an integer number.

val n1: Int = 125
val ch: Char = n1.toChar() // '}'
val n2: Int = ch.toInt()   // 125

If you have a value of a floating-point type (e.g., Double), you may convert it to a value of an integer type such as Int or Long.

val d: Double = 12.5
val n: Long = d.toLong() // 12

As you can see, the fractional part is simply ignored.

Also, you can convert a number from a larger type (e.g. Long or Double) to a smaller type (e.g., Int) using the functions mentioned above.

val d: Double = 10.2
val n: Long = 15

val res1: Int = d.toInt() // 10
val res2: Int = n.toInt() // 15

However, this conversion may truncate the value, because Long and Double can store a much larger number than Int.

val bigNum: Long = 100_000_000_000_000

val n: Int = bigNum.toInt() // 276447232; oops

Oy va voi! The value has been truncated. This problem is known as type overflow. The same problem may occur when you convert Int to Short or Byte. What do we learn from here? Convert from a larger type to a smaller type only when you are absolutely sure that it is necessary, and that truncation will not interfere with your program.

Converting to and from a String

Sometimes you need to get a string representation of a number or value of another type. Kotlin provides a useful function called toString() for converting something to a string.

val n = 8     // Int
val d = 10.09 // Double
val c = '@'   // Char
val b = true  // Boolean

val s1 = n.toString() // "8"
val s2 = d.toString() // "10.09"
val s3 = c.toString() // "@"
val s4 = b.toString() // "true"

A string can be converted to a number or even a boolean value (but not to a single character).

val n = "8".toInt() // Int
val d = "10.09".toDouble() // Double
val b = "true".toBoolean() // Boolean

If a string representation of a number has an invalid format, an error called an exception will occur during the conversion. The program will stop if you do not take special actions, which we will discuss later.

However, if you convert a string to a boolean value, no errors occur. If the string is "true", ignoring case, the result of the conversion will be true, otherwise false.

val b1 = "false".toBoolean() // false
val b2 = "tru".toBoolean()   // false
val b3 = "true".toBoolean()  // true
val b4 = "TRUE".toBoolean()  // true

Demonstration

The program below will demonstrate the functions discussed above. It reads a string representation of a number, converts it to several other types, then prints the results of all the conversions.

fun main() {
    val something = readLine().toString()

    val d = something.toDouble()
    val f = d.toFloat()
    val i = f.toInt()
    val b = i.toByte()

    println(d)
    println(f)
    println(i)
    println(b)
    println(something.toBoolean())
}

Imagine we have the following input:

1000.0123456789

The program prints:

1000.0123456789
1000.0123
1000
-24
false

Let's take a closer look at the output. The number represented by a string is successfully converted to Double because it has a suitable format. This number can be saved in Double without loss. Then the number is converted to Float with a loss because this type can store fewer decimal numbers. The conversion to Int just cuts the fractional part. The number 1000 is larger than Byte can store (from -128 to 127), so here is a type overflow (-24). The result of converting the input string to Boolean is false, because the value is not "true".

We hope this lesson has helped you understand the principles of conversion between basic data types.