Wednesday, 22 November 2017

Kotlin: Numbers

Kotlin provides below data types to support numbers.

Data Type
Size in Bits
Double
64
Float
32
Long
64
Int
32
Short
16
Byte
8

Numbers.kt
fun main(args: Array<String>) {
 var doubleVar: Double = 1.23
 var floatVar: Float = 1.23f
 var longVar: Long = 123
 var intVar: Int = 123
 var shortVar: Short = 123
 var byteVar: Byte = 123


 println("doubleVar : ${doubleVar}")
 println("doubleVar : ${floatVar}")
 println("longVar : ${longVar}")
 println("intVar : ${intVar}")
 println("shortVar : ${shortVar}")
 println("byteVar : ${byteVar}")
}

Output
doubleVar : 1.23
doubleVar : 1.23
longVar : 123
intVar : 123
shortVar : 123
byteVar : 123

Hexa, octal and Binary literal notation
Kotlin support Hexa and binary notation, but not support octal notation. Hexa numbers are represented by prefixing 0x,


Numbers.kt

fun main(args: Array<String>) {
 var hexaNum : Int = 0x123
 var binaryNum : Int = 0b10101010

 println("hexaNum : ${hexaNum}")
 println("binaryNum : ${binaryNum}")
}

Output

hexaNum : 291
binaryNum : 170


You can also represent numbers using ‘_’.


Numbers.kt
fun main(args: Array<String>) {

 var ten = 10
 var hundred = 100
 var thousand = 1000
 var tenThousand = 10_000
 var oneLaksh = 100_000
 var tenLaksh = 1_000_000

 println("ten : ${ten}")
 println("hundred : ${hundred}")
 println("thousand : ${thousand}")
 println("tenThousand : ${tenThousand}")
 println("oneLaksh : ${oneLaksh}")
 println("tenLaksh : ${tenLaksh}")
}


Output
ten : 10
hundred : 100
thousand : 1000
tenThousand : 10000
oneLaksh : 100000
tenLaksh : 1000000



Previous                                                 Next                                                 Home

No comments:

Post a Comment