Floating points are fractions (decimal numbers), they can be signed or unsigned.
Examples : -11.456, 30.12, 0.5
Swift supports both signed and unsigned floating points. They range of floating points are much larger than that of
integers. There are two types of floating points numbers in Swift
1. Double
2. Float
1. Double
Double is a 64-bit floating point number. It should be used when a floating number is too large.
Syntax : var constantName:Double = value => Explicit way of declaring a Double
Syntax : var constantName = value => Implicit way of declaring a Double
//
// main.swift
// Swift Tutorials 2014-15
// Double in Swift
//
// Created by Code2care on 15/09/14.
// Copyright (c) 2014 Code2care. All rights reserved.
//
var myDoubleA:Double = 30.20
var myDoubleB:Double = 3/2
println("\(myDoubleA)")
println("\(myDoubleB)")
Output :
30.2
1.5
Program ended with exit code: 0
2. Float
Float is a 32-bit floating point number. It should be used when you do not have a decimal number that is as large as 64-bit. Floats have a lesser decimal precision than Double
Syntax : var constantName:Float = value => Explicit way of declaring a Float
Syntax : var constantName = value => Implicit way of declaring a Float
//
// main.swift
// Swift Tutorials 2014-15
// Double in Swift
//
// Created by Code2care on 15/09/14.
// Copyright (c) 2014 Code2care. All rights reserved.
//
var myFloatA:Float = 11.50
var myFloatB:Float = 32/2123
println("\(myFloatA)")
println("\(myFloatB)")
Output :
11.5
0.0150730097666383
Program ended with exit code: 0
Note : Swift is a type safe language, when you assign a variable or a constant a decimal number, it always chooses it to be a Double rather then a float.
When we combine a Int with a Float the resulting value is of type Double
Example : var total = 23 + 1.3040 : total will be assigned as Double.