Number Data type Usage and Type Conversion in Kotlin


Definition

  • There are 6 built-in types of numbers in Kotlin. They are
    • Double
    • Float
    • Long
    • Int
    • Short
    • Byte
  • Double and Float are floating point numbers. 
  • The type can be either declared explicitly or the compiler itself has the ability to infer the type of the assigned value.

Syntax and declaration

Thus a Number can be declared by 3 ways as mentioned below.

1. Mentioning type explicitly

val variable_name : Number = value

for example,

val number : Number = 100f

2. Number type is automatically inferred

val variable_name = value

for example,
//Number type is automatically inferred
val number = 100

3. Declaring and Initializing separately

var variable_name : Number 
variable_name = value

for example

//Declaring and Initializing separately
var number:Number 
number = 100.57

Number Datatype Example Program in Kotlin

// Number Datatype Kotlin example program
// Data type Kotlin Programs, Basic Kotlin Programs

fun main(args:Array<String>) {
    //Assigning value to Number variable explicitly and is automatically cast to Float Number
    val a:Number = 22.8f
    //Assigned value is inferred automatically by compiler and is automatically cast to Float Number
    val b = 100.0f

    println("Value of a is $a")
    println("Value of b is $b")
}

Sample Output

Value of a is 22.8
Value of b is 100.0

Type conversion syntax and declaration

//Number to Double Conversion 
val variable_name = number_variable.toDouble()

//Number to Int Conversion 
val variable_name = number_variable.toInt()

Number type Conversion Example Program in Kotlin
 

// Number Datatype Kotlin example program
// Data type Kotlin Programs, Basic Kotlin Programs

fun main(args: Array < String > ) {
	val number : Number = 100.2
	//Conversion to Float
    val num1: Float = number.toFloat()
    //Conversion to Int
    val num2: Int = number.toInt()
	//Conversion to Double
    val num3: Double = number.toDouble()
    //Conversion to Byte
    val num4: Byte = number.toByte()

    //Print values after conversion
    println("Number to Float : number Value : $num1")
    println("Number to Int : number Value : $num2")
    println("Number to Double : number Value : $num3")
    println("Number to Byte : number Value : $num4")
}

Sample Output

Number to Float : number Value : 100.2
Number to Int : number Value : 100
Number to Double : number Value : 100.2
Number to Byte : number Value : 100