Instruction 3

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Learning Basic Data Types: Numbers

Types are how we identify different kinds of data from the real world. Kotlin has many different basic types, including integers, floating-point numbers, booleans, characters, and strings. In this lesson, you’ll cover the number types.

Int

In Kotlin, every numeric value is automatically an Int. An Int has a maximum and minimum value of between -2,147,483,648 (-2^31^) and 2,147,483,647 (-2^31^ - 1). If a value exceeds this limit, the variable becomes a Long. A Long is also a whole number but has a higher capacity than an Int. You have already used the Int type in the previous examples. To initialize a Long, append an L to the number:

fun main() {
  val amount = 100L
  println(amount)
}
fun main() {
  val amount = 12_000_000_000
  println(amount)
}

Floating-point

Floating-point types are numbers with decimals or fractions. Single-precision or decimal numbers holding 32 bits of data, are assigned the Float class type when creating variables. Your program at this point handles the Int type only. This is enforced by toInt():

import java.util.Calendar

const val WEEKLY_INTEREST = 100

fun main(args: Array<String>) {
  val mondayAmount = args[0].toInt()
  val tuesdayAmount = args[1].toInt()
  val wednesdayAmount = args[2].toInt()
  val thursdayAmount = args[3].toInt()
  val fridayAmount = args[4].toInt()
  var totalWeeklyAmount = mondayAmount + tuesdayAmount + wednesdayAmount + thursdayAmount + fridayAmount

  totalWeeklyAmount = totalWeeklyAmount + WEEKLY_INTEREST

  val weekNumber = getWeekNumber()
  println("In week number $weekNumber, you have saved $$totalWeeklyAmount.")
}

fun getWeekNumber(): Int {
  val calendar: Calendar = Calendar.getInstance()
  val weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR)
  return weekOfYear
}
Exception in thread "main" java.lang.NumberFormatException: For input string: "15.0"
at java.lang.NumberFormatException.forInputString (:-1)
at java.lang.Integer.parseInt (:-1)
at java.lang.Integer.parseInt (:-1)
  val mondayAmount = args[0].toFloat()
  val tuesdayAmount = args[1].toFloat()
  val wednesdayAmount = args[2].toFloat()
  val thursdayAmount = args[3].toFloat()
  val fridayAmount = args[4].toFloat()
In week number 3, you have saved $442.0.
fun main() {
  val amount = 100f
  println(amount)
}

Double

For higher or double-precision numeric data, use the Double class type. The Double stores 64-bits of numeric data. To initialize a Double, use precision or a decimal point.

val amount = 100.0
println(amount)
val amount = 12_000_000_000
println(amount)
See forum comments
Download course materials from Github
Previous: Instruction 2 Next: Instruction 4