...

/

Numeric Conversions and Operations

Numeric Conversions and Operations

Discover bitwise operations and precise arithmetic operations with BigDecimal and BigInteger, including bitwise methods and handling unlimited number sizes.

Underscores in numbers

In number literals, we can use the underscore (_) between digits. This character is ignored, but we sometimes use it to format long numbers for better readability.

Press + to interact
fun main() {
val million = 1_000_000
println(million) // 1000000
}

Other numeral systems

To define a number using the hexadecimal numeral system, start with 0x. To define a number using the binary numeral system, start with 0b. The octal numeral system is not supported.

Press + to interact
fun main() {
val hexBytes = 0xA4_D6_FE_FE
println(hexBytes) // 2765553406
val bytes = 0b01010010_01101101_11101000_10010010
println(bytes) // 1382934674
}

The Number type and conversion functions

All basic types that represent numbers are subtypes of the Number type.

Press + to interact
fun main() {
val i: Int = 123
val b: Byte = 123
val l: Long = 123L
val n1: Number = i
val n2: Number = b
val n3: Number = l
println("n1: $n1")
println("n2: $n2")
println("n3: $n3")
}

The Number type specifies transformation functions: from the current number to any other basic type representing a number.

Press + to interact
abstract class Number {
abstract fun toDouble(): Double
abstract fun toFloat(): Float
abstract fun toLong(): Long
abstract fun toInt(): Int
abstract fun toChar(): Char
abstract fun toShort(): Short
abstract fun toByte(): Byte
}

This means that we can transform each basic number into a different one using the to{new type} function. Such functions are known as conversion functions.

Press + to interact
fun main() {
val b: Byte = 123
val l: Long = b.toLong()
val f: Float = l.toFloat()
val i: Int = f.toInt()
val d: Double = i.toDouble()
println("b: $b")
println("l: $l")
println("f: $f")
println("i: $i")
println("d: $d")
}

Operations on numbers

Numbers in ...