Floating-point numbers are numbers with fractional parts.
Examples of floating-point numbers are 0.0123, 2.45, and -4.521.
In Swift, there are two floating-point types: Float and Double.
Float uses 32 bits for storage and Double uses 64 bits.
This can be confirmed using the sizeof() function:
print("Size of Double: \(sizeof(Double)) bytes") print("Size of Float: \(sizeof(Float)) bytes")
Double has a precision of at least 15 decimal digits, while Float has a precision of at least six decimal digits.
When assigning a floating-point number to a constant or variable, Swift will always infer the Double type unless you explicitly specify otherwise:
var num1 = 3.14 //num1 is Double var num2: Float = 3.14 //num2 is Float
If you try to assign a Double to a Float type, the compiler will error out:
num2 = num1 //num1 is Double and num2 is Float
This is because the number stored in a Double type may not be able to fit into a Float type, and result in an overflow.
To assign num1 to num2 , explicitly cast num1 to a Float:
num2 = Float (num1)