Swift has two data types (Double and Float) to hold the decimal values. Both of them hold the same decimal type values but have some differences.
The basic difference is around the size of memory they both use based on which their precision varies.
Let’s try to understand the differences between both with example.
Number of Digits
- The
Double
type is used to store values in up to 17 places. It starts from the leftmost side and reduces the digits from the right side of the value if exceeding 17 places. - The
Float
type is used to store values in up to 8 places. It also starts from the leftmost side and reduces the digits from the right side of the value if exceeding 8 places.
var doubleVariable : Double = 1234567890.1234567890
var floatVariable : Float = 12345.12345
print(doubleVariable)
//this will print only 17 digits from left
//1234567890.1234567
print(floatVariable)
//this will print only 8 digits from left
//12345.123
Memory Size
Double
takes 8 bytes of memory.Float
takes only 4 bytes of memory
var doubleVariable : Double = 1234567890.1234567890
var floatVariable : Float = 12345.12345
print(MemoryLayout.size(ofValue: doubleVariable))
//this will print
//8 (bytes)
print(MemoryLayout.size(ofValue: floatVariable))
//this will print
//4 (bytes)
Default Type
- If we don’t define any type and directly assign the value, the compiler initialises it as
Double
.
var defaultVariable = 1.00
var doubleVariable : Double = 1234567890.1234567890
var floatVariable : Float = 12345.12345
print(type(of: defaultVariable))
//this will print
//Double
print(type(of: doubleVariable))
//this will print
//Double
print(type(of: floatVariable))
//this will print
//Float
Conclusion
- The
Double
is more precise than theFloat
as it has more decimal digits. - The
Double
takes more memory than theFloat
. - If there no data type is defined explicitly and if we assign any decimal value to a variable, the compiler treats it as
Double
.
When to Use What
- For places where no extra precision is required, use
Float
. Like amount where up to 2 decimal digits can work. - If confused about what to use and not sure where the value can go, use
Double
.