0
0
Swiftprogramming~5 mins

Int, Double, Float number types in Swift

Choose your learning style9 modes available
Introduction

We use Int, Double, and Float to store numbers in Swift. Each type helps us keep different kinds of numbers, like whole numbers or numbers with decimals.

When you need to count things like apples or books (use Int).
When you want to store precise decimal numbers like money or measurements (use Double).
When you want to save memory and can accept less precision for decimal numbers (use Float).
Syntax
Swift
var wholeNumber: Int = 10
var decimalNumber: Double = 3.14
var smallerDecimal: Float = 2.5

Int stores whole numbers without decimals.

Double stores decimal numbers with high precision.

Float stores decimal numbers but with less precision and uses less memory.

Examples
This stores a whole number representing age.
Swift
var age: Int = 25
This stores a precise decimal number for pi.
Swift
var pi: Double = 3.14159
This stores a decimal number for temperature with less precision.
Swift
var temperature: Float = 36.6
You can let Swift guess the type if you assign a value directly.
Swift
var count = 100 // Swift infers this as Int
Sample Program

This program counts apples and calculates total cost using Int and Double types. It shows how to convert Int to Double for calculation.

Swift
import Foundation

var apples: Int = 5
var pricePerApple: Double = 0.99
var totalCost: Double = Double(apples) * pricePerApple

print("You bought \(apples) apples.")
print("Each apple costs $\(pricePerApple).")
print("Total cost is $\(totalCost).")
OutputSuccess
Important Notes

You cannot directly multiply Int and Double without converting one type to the other.

Double is preferred for most decimal numbers because it is more precise than Float.

Use Int when you only need whole numbers to save memory and avoid decimals.

Summary

Int stores whole numbers.

Double stores precise decimal numbers.

Float stores decimal numbers with less precision and uses less memory.