Doubles and Floats
Declaring Doubles
Double is Swift's default floating-point type, used automatically when a literal contains a decimal point.
Example: Declaring Doubles
let price = 19.99
let taxRate = 0.08
print("Price: \(price), tax rate: \(taxRate)")
Login to try C/C++/Java/PHP code in the editor
Float vs Double
Float uses less memory (32 bits) but has less precision than Double (64 bits). Swift infers Double by default, so Float must be requested with an explicit annotation.
Example: Float vs Double
let preciseValue: Double = 3.14159265358979
let lessPrecise: Float = 3.14159265358979
print("Double: \(preciseValue)")
print("Float: \(lessPrecise)")
Login to try C/C++/Java/PHP code in the editor
Converting Between Int and Double
Swift never silently converts between numeric types; you must explicitly wrap a value, such as Double(someInt), to convert an integer into a floating-point number for calculations.
Note: Without Double(items), dividing a Double by an Int would not even compile -- Swift requires matching types.
Example: Converting Between Int and Double
let items = 3
let totalCost = 10.0
let average = totalCost / Double(items)
print("Average cost per item: \(average)")
Login to try C/C++/Java/PHP code in the editor
- Comparing two
Doublevalues with==after arithmetic and expecting exact equality, when floating-point rounding can make them differ slightly. - Using
FloatwhenDoubleis intended;Doubleis Swift's default and has more precision, so mixing them requires explicit conversion. - Dividing two
Intvalues expecting a decimal result, forgetting thatInt / Inttruncates instead of producing aDouble.
Doubleis a 64-bit floating-point type and Swift's default choice for decimal numbers.Floatis a 32-bit floating-point type, less precise but sometimes used to save memory.- Floating-point arithmetic can have small rounding errors, so avoid exact
==comparisons. - Converting an
Intto aDoublerequires an explicitDouble(someInt)call.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: