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.
fun main() {val million = 1_000_000println(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.
fun main() {val hexBytes = 0xA4_D6_FE_FEprintln(hexBytes) // 2765553406val bytes = 0b01010010_01101101_11101000_10010010println(bytes) // 1382934674}
The Number
type and conversion functions
All basic types that represent numbers are subtypes of the Number
type.
fun main() {val i: Int = 123val b: Byte = 123val l: Long = 123Lval n1: Number = ival n2: Number = bval n3: Number = lprintln("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.
abstract class Number {abstract fun toDouble(): Doubleabstract fun toFloat(): Floatabstract fun toLong(): Longabstract fun toInt(): Intabstract fun toChar(): Charabstract fun toShort(): Shortabstract 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.
fun main() {val b: Byte = 123val 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 ...