1.5. Floating point numbers and Type annotation

Two basic data types in Swift handle the floating point numbers (fractional values): Double and Float.

Double is short for "double-precision floating point number." It is a 64-bit floating point number. Long story short, it can hold very large fractional values. Swift uses Double as its default data type for floating point literals.

On the other hand, Float is a 32-bit floating point number, which is less precise than Double, and you do not need to use it unless you are building games or graphics applications.

So now, let's write a Double variable:

var myNum = 12.5
print(myNum)
print(type(of: myNum))

Here Swift automatically sets the type of the variable myNum to Double since I put a fractional value to it. The above code outputs the following:

The first print() outputs the value of myNum, and the second print outputs the type of the variable myNum.

Now, if you need to define a Float at some point**,** how would you do it? Remember, Swift, by default, uses Double for fractional values. That's where we will learn how to create a variable with a predefined type. For example, in the following code, I am creating a Float variable:

Here, I am writing 'var' to say the next one is a variable, as earlier. I give the variable a name, 'myFloat', and then I put a colon(:), followed by the type of the variable (Float), and finally, I assign a value, 13. This is a standard way of defining a variable in Swift. We will eventually learn about a more concrete way of declaring and defining the variables. Now the output of the code is:

One thing to note is that I put the value as 13 for myFloat, which would be interpreted as an Int if I did not specifically predefine it as a Float. If you look at the output, 13 became 13.0, which is a fractional number.

Video

Last updated

Was this helpful?