Swift Floating-Point Numbers
What Are Floating-Point Numbers in Swift?
Floating-point numbers in Swift store decimal values, making them ideal for handling fractional numbers like 3.2232, 92.2, and 21.2. The Float data type is a 32-bit floating-point number that provides a precision of at least six decimal places.
Why Use Floating-Point Numbers?
Swift allows you to perform various arithmetic operations on floating-point numbers, including:
- Addition
- Subtraction
- Multiplication
- Division
-
Comparison (Equal to
==
, Not Equal to!=
)
Float Data Type Syntax
Here’s how you declare a floating-point number in Swift:
let num: Float = 2.3421
Shorthand Declaration
let num = 3.21 // Swift infers it as a Float or Double
Example 1: Multiply Two Floating-Point Numbers
import
Foundation
// Define Float variables
var num1:
Float =
2.342
var num2:
Float =
23.44
// Calculate the product
var result:
Float =
num1 *
num2
// Print the result
print("Product of \(num1) *
\(num2) is
\(result) ")
Output
Understanding Swift - Double
The Double data type in Swift is used to store decimal numbers with high precision. It is a 64-bit floating-point number that can store values up to 15 decimal places, making it more accurate than Float.
Why Use Double in Swift?
- Higher precision than Float.
- Default type for decimal numbers if not explicitly defined.
- Ideal for financial calculations and scientific computations.
Syntax of Double in Swift
Standard Syntax:let num:Double = 923.890
let num= 923.890
Example 1: Sum of Two Double Numbers
import Foundation
// Defining double numbers
let num1: Double = 2.3764
let num2: Double = 12.738
// Store the sum
let sum = num1 + num2
print ("Sum of \(num1) and \(num2) = \(sum) ")
Difference Between Float and Double in Swift
Feature | Double | Float |
---|---|---|
Precision | At least 15 decimal digits | At least 6 decimal digits |
Memory Size | 8 bytes | 4 bytes |
Default Type | Yes, if no type is defined | No, not preferred by the compiler |