Numeric literals let you write numbers directly in your code. They help you tell the computer exact values to use.
0
0
Numeric literal formats in Swift
Introduction
When you want to assign a number to a variable or constant.
When you need to write numbers in different bases like binary or hexadecimal.
When you want to make large numbers easier to read by adding underscores.
When you want to specify floating-point numbers with decimals.
When you want to use scientific notation for very big or very small numbers.
Syntax
Swift
let decimal = 1234 let binary = 0b1001 let octal = 0o17 let hex = 0x1F let floatNum = 12.34 let expNum = 1.2e3 let readableNum = 1_000_000
Numeric literals can be decimal, binary (start with 0b), octal (0o), or hexadecimal (0x).
Underscores (_) can be used inside numbers to improve readability without changing the value.
Examples
A simple decimal number.
Swift
let decimal = 42
A binary number representing 10 in decimal.
Swift
let binary = 0b1010
A hexadecimal number representing 255 in decimal.
Swift
let hex = 0xFF
Using underscores to make a large number easier to read.
Swift
let largeNumber = 1_000_000
Sample Program
This program shows different numeric literal formats in Swift and prints their decimal values.
Swift
import Foundation let decimal = 100 let binary = 0b1100100 let octal = 0o144 let hex = 0x64 let floatNum = 123.45 let expNum = 1.2345e2 let readableNum = 1_000_000 print("Decimal: \(decimal)") print("Binary: \(binary)") print("Octal: \(octal)") print("Hexadecimal: \(hex)") print("Float: \(floatNum)") print("Exponential: \(expNum)") print("Readable number: \(readableNum)")
OutputSuccess
Important Notes
All numeric literals represent the same value regardless of format when printed as decimal.
Floating-point literals can use decimal points or exponential notation.
Underscores do not affect the value but help you read large numbers easily.
Summary
Numeric literals let you write numbers in decimal, binary, octal, or hexadecimal.
You can use underscores to make numbers easier to read.
Floating-point numbers can be written with decimals or scientific notation.