Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Floating-Point Numbers in Swift
Written by Team Kodeco

Floating-point numbers, also known as floats, are numbers with decimal points. In Swift, there are two types of floating-point numbers: Float and Double. Float is a 32-bit number, whereas Double is a 64-bit number.

To declare a floating-point variable, use the keyword var or let followed by the variable name and assign it a value.

var pi: Float = 3.14
let e: Double = 2.71828
let rating = 2.5 // Using type inference
print(type(of: rating)) // Prints Double

You can also perform mathematical operations with floating-point numbers such as addition, subtraction, multiplication, and division.

var x = 3.14
var y = 2.71
var sum = x + y  //5.85
var difference = x - y  //0.43
var product = x * y //8.51
var quotient = x / y //1.15

It’s worth noting that, due to the nature of floating-point numbers, the results of certain operations may not always be completely accurate. This could lead to unexpected results when comparing or rounding floating-point numbers.

© 2024 Kodeco Inc.