Numbers
Kotlin provides the built-in numeric classes.
type | size (bits) | values |
---|---|---|
Byte | 8 | [-128; 127] |
Short | 16 | [-32768; 32767] |
Int | 32 | [-231; 231 - 1] |
Long | 64 | [-263; 263 - 1] |
Float | 32 24 significant bits 8 exponent bits |
Can have 6-7 decimal digits. If a value contains more than 6-7 decimal digits, it will be rounded. |
Double | 64 53 significant bits 11 exponent bits |
Can have 15-16 decimal digits. |
val one = 1 // Int
val threeBillion = 3000000000 // Long
val oneLong = 1L // Long
val oneByte: Byte = 1
val pi = 3.14 // Double
val e = 2.7182818284 // Double
val eFloat = 2.7182818284f // Float, actual value is 2.7182817
conversion
There are no implicit widening conversions for numbers in Kotlin. And smaller types are not subtypes of bigger ones. You must use the converion methods.
if(oneLong==oneInt){}
if(oneLong==oneInt.toLong()){}
Absence of implicit conversions is rarely noticeable because the type is inferred from the context, and arithmetical operations are overloaded for appropriate conversions
val l = 1L + 3 // Long + Int => Long
All numeric classes have the following conversion methods.
method | description |
---|---|
toByte() | Converts this value to Byte. |
toShort() | Converts this value to Short. |
toInt() | Converts this value to Int. |
toLong() | Converts this value to Long. |
toFloat() | Converts this value to Float. |
toDouble() | Converts this value to Double. |
toChar() | Converts this value to Char. |