Floating-point and Double values

A floating-point number is a number with a decimal component. There are two standard floating-point types in Swift: Float and Double. The Float type represents a 32-bit floating-point number, while the Double type represents a 64-bit floating-point number. Swift also supports an extended floating-point type: Float80. The Float80 type is an 80-bit floating-point number.

It is recommended that we use the Double type over the Float type unless there is a specific reason to use the latter. The Double type has a precision of at least 15 decimal digits, while the Float type's precision can be as small as six decimal digits. Let's look at an example of how this can affect our application without us knowing it. The following screenshot shows the results if we add two decimal numbers together using both a Float type and a Double type:

As we can see from the screenshot, the two decimal numbers that we are adding contain nine digits past the decimal point; however, the results in the Float type only contain seven digits, while the results in the Double type contain the full nine digits. The loss of precision can cause issues if we are working with currency or other numbers that need accurate calculations.

The floating-point accuracy problem is not an issue confined to Swift; all the languages that implement the IEEE 754 floating-point standard have similar issues. The best practice is to use the Double type for all floating-point numbers unless there is a specific reason not to.

What if we have two variables, where one is an integer and the other is a double? Do you think we can add them as the following code shows?

var a: Int = 3 
var b: Double = 0.14 
var c = a + b 

If we put the preceding code into a Playground, we would receive the following error:

operator '+' cannot be applied to operands of type Int and Double 

This error lets us know that we are trying to add two different types of numbers, which is not allowed. To add an integer and a double together, we need to convert the integer value into a double value. The following code shows how to do this:

var a: Int = 3 
var b: Double = 0.14  
var c = Double(a) + b 

Notice how we use the Double() function to initialize a Double value with the integer value. All numeric types in Swift have an initializer to do these types of conversion. These initializers are called convenience initializers, similar to the Double() function shown in the preceding code sample. For example, the following code shows how you can initialize a Float or uint16 value with an integer value:

var intVar = 32 
var floatVar = Float(intVar) 
var uint16Var = UInt16(intVar) 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset