0
0
Kotlinprogramming~5 mins

Number literal formats (underscore, hex, binary) in Kotlin

Choose your learning style9 modes available
Introduction

Number literals let you write numbers in your code clearly and in different styles. Using underscores, hex, or binary makes numbers easier to read or match real-world formats.

When you want to write large numbers clearly, like 1_000_000 instead of 1000000.
When you need to work with colors or memory addresses, which are often shown in hexadecimal (hex).
When dealing with bits or flags, binary numbers help you see the exact bits set.
When you want to improve code readability by grouping digits logically.
When you want to match number formats used in hardware or protocols.
Syntax
Kotlin
val decimal = 1_000_000
val hex = 0xFF_EC_DE_5E
val binary = 0b1101_0101

Underscores (_) can be placed anywhere between digits to improve readability.

Hex numbers start with 0x and binary numbers start with 0b.

Examples
Underscores make the large number easier to read.
Kotlin
val million = 1_000_000
Hexadecimal number with underscores for clarity, often used for colors.
Kotlin
val color = 0xFF_EC_DE_5E
Binary number with underscores to separate bits visually.
Kotlin
val flags = 0b1101_0101
Sample Program

This program shows how to write and print numbers using underscores, hex, and binary formats.

Kotlin
fun main() {
    val decimal = 1_000_000
    val hex = 0xFF_EC_DE_5E
    val binary = 0b1101_0101

    println("Decimal: $decimal")
    println("Hex: $hex")
    println("Binary: $binary")
}
OutputSuccess
Important Notes

Underscores cannot be at the start or end of a number, or next to the prefix (0x, 0b).

Hex and binary literals are converted to decimal values when used in calculations or printed.

Summary

Use underscores to make numbers easier to read.

Hex numbers start with 0x and are useful for colors and memory values.

Binary numbers start with 0b and help when working with bits.