How to find max value for Double and Float in Swift
As of Swift 3+, you should use:
CGFloat.greatestFiniteMagnitudeDouble.greatestFiniteMagnitudeFloat.greatestFiniteMagnitude
While there’s no Double.max
, it is defined in the C float.h
header, which you can access in Swift via import Darwin
.
import Darwinlet fmax = FLT_MAXlet dmax = DBL_MAX
These are roughly 3.4 * 10^38
and 1.79 * 10^308
respectively.
But bear in mind it’s not so simple with floating point numbers (it’s never simple with floating point numbers). When holding numbers this large, you lose precision in a similar way to losing precision with very small numbers, so:
let d = DBL_MAXlet e = d - 1.0let diff = d - ediff == 0.0 // truelet maxPlusOne = DBL_MAX + 1maxPlusOne == d // truelet inf = DBL_MAX * 2// perhaps infinity is the “maximum” inf == Double.infinity // true
So before you get into some calculations that might possibly brush up against these limits, you should probably read up on floating point. Here and here are probably a good start.
AV's answer is fine, but I find those macros hard to remember and a bit non-obvious, so eventually I made Double.MIN
and friends work:
extension Double { static var MIN = -DBL_MAX static var MAX_NEG = -DBL_MIN static var MIN_POS = DBL_MIN static var MAX = DBL_MAX}
Don't use lowercase min and max -- those symbols are used in Swift 3.