Numbers and explicit conversions
Numbers and explicit conversions
A class total is a whole number, while its average can contain a fraction. Kotlin provides numeric types such as Int, Long and Double. The chosen type affects valid operations and results, so integer arithmetic is not interchangeable with floating-point arithmetic.
What you’ll learn
- Convert before calculating a fractional average.
- Handle text that cannot become an integer.
Numbers and explicit conversions in the example
Integer operands
A class total is a whole number, while its average can contain a fraction.
Integer operandsConvert before division
Convert deliberately with <code>toDouble()</code> before fractional division.
Convert before divisionFractional result
Integer division produces 77.
Fractional result
Understand numbers and explicit conversions
Convert deliberately with toDouble() before fractional division. Parse arbitrary text with toIntOrNull() when invalid input should become absence rather than an exception. A successful numeric conversion still does not validate whether a mark is within the school’s allowed range.
Follow numbers and explicit conversions
Save the complete source as Main.kt and use the Kotlin/JVM environment. No separate input file is needed.
Kotlin/JVM · complete program
fun main() {
val total = 155
println(total / 2)
println(total.toDouble() / 2)
println("eighty".toIntOrNull() ?: -1)
}Expected output
77
77.5
-1Follow the execution
Integer division produces 77. Converting the total gives 77.5. The invalid text has no parsed integer, so the Elvis fallback displays -1. That fallback is a demonstration marker, not a valid student mark.
Try this in the Kotlin compiler by pasting the complete program.
Practice: Numbers and explicit conversions
Your task: Why does the first division not display 77.5?
Kotlin/JVM · complete program
fun main() {
val total = 155
println(total / 2)
println(total.toDouble() / 2)
println("eighty".toIntOrNull() ?: -1)
}Worked answer
Both operands use integer arithmetic, which truncates the fractional part here. Convert a suitable operand to Double before division when a fractional result is required.
Numbers and explicit conversions: the important boundary
Int arithmetic can overflow, and floating-point numbers approximate many decimal values. Choose types and range checks from the domain. Converting a large value to a smaller numeric type can lose information.
Check your understanding
Numbers and explicit conversions: what to keep in mind
Both operands use integer arithmetic, which truncates the fractional part here. Convert a suitable operand to Double before division when a fractional result is required. Int arithmetic can overflow, and floating-point numbers approximate many decimal values.
Further reading: official Kotlin documentation for this topic.
Reaching the recap and completing the quizzes are separate milestones.