Floating-point numbers are numbers that have a decimal point. They can be used to represent real numbers, such as the weight of a person or the temperature of a room. They can also be used to represent imaginary numbers, such as the square root of -1.
In Swift, there are two types of floating-point numbers:
- Float represents a 32-bit floating-point number. It can hold 6 to 9 decimal digits.
- Double represents a 64-bit floating-point number. It can hold 15 to 17 decimal digits.
Double has greater precision and a larger range than Float, but it also takes up more memory. It is recommended to use Double unless you have a specific reason to use Float.
To declare a floating-point variable, use the following syntax:
var variable_name: Float // or Double
For example, the following code declares a floating-point variable named "my_number" and assigns it the value 1.23:
var my_number: Float = 1.23
Floating-point numbers can be added, subtracted, multiplied, and divided using the same operators as integers.
For example, the following code adds the floating-point numbers 1.23 and 4.56 and assigns the result to the variable "sum":
var sum: Float = 1.23 + 4.56
The result of the addition operation is 5.79.
Floating-point numbers can also be used in expressions.
For example, the following code calculates the area of a circle with a radius of 5.0:
var area: Float = 3.14 * 5.0 * 5.0
The result of the calculation is 78.54.
Floating-point numbers can be used in a variety of ways in Swift. They can be used to represent real numbers, imaginary numbers, and to perform calculations.
Here are some additional things to keep in mind about floating-point numbers in Swift:
- Floating-point numbers are not exact. They are represented as approximations, so there may be rounding errors when performing calculations.
- Floating-point numbers are not always the best choice for representing numbers. If you need to represent numbers with a high degree of precision, you may want to use a different type of number, such as a decimal number.