-
Book Overview & Buying
-
Table Of Contents
Android Programming for Beginners - Fourth Edition
By :
We have already seen numerous ways we can declare, change, perform calculations on, and reassign all manner of types of both val and var. But what happens if we have an Int and we absolutely must have a Float, or when we have a Double, and we really need a String version of the value?
What follows is a super-fast run-down of some of the ways we can convert between types. And, as we have come to expect, Kotlin provides many convenient ways to do this. Let's talk about conversion functions.
The first conversion function we will look at is toInt. This function converts a fractional number to an Int by truncating the fractional part.
val x = 10.9
val result = x.toInt()
Log.d("Example", "toInt result: $result")
In the preceding code, we declare a Double (the type is inferred) called x and assign the value 10.9. We then assign the result of x.toInt() to the result variable. The preceding code would output toInt result: 10, showing that the decimal...