In Swift, how can one check if a string is a valid double value? I have been using the following extension from this question (but as a float) but if the value cannot be converted, it simply returns "0":
extension String {
var doubleValue:Double? {
return (self as NSString).doubleValue
}
}
Ideally, I would like it to return nil
so it can be caught in an if-let
, like so:
if let i = str.doubleValue {
object.price = i
} else {
// Tell user the value is invalid
}
The Double data type is the standard Swift way of storing decimal numbers such as 3.1, 3.14159 and 16777216.333921.
Swift provides two signed floating-point number types: Double represents a 64-bit floating-point number. Float represents a 32-bit floating-point number.
Convert Swift String to DoubleUse Double , Float , CGFloat to convert floating-point values (real numbers). let lessPrecisePI = Float("3.14") let morePrecisePI = Double("3.1415926536") let width = CGFloat(Double("200.0")!)
Integers are whole numbers that can be negative, zero, or positive and cannot have a fractional component. In programming, zero and positive integers are termed as “unsigned”, and the negative ones are “signed”.
It is indeed more efficient not to create a number formatter every time we do a conversion:
extension String {
struct NumFormatter {
static let instance = NumberFormatter()
}
var doubleValue: Double? {
return NumFormatter.instance.number(from: self)?.doubleValue
}
var integerValue: Int? {
return NumFormatter.instance.number(from: self)?.intValue
}
}
edit/update: Xcode 11 or later • Swift 5.1 or later
You can use Double
initializer init?<S>(_ text: S) where S : StringProtocol
to create an instance property on StringProtocol
and use it to check if a String
or Substring
is a valid Double
:
extension StringProtocol {
var double: Double? { Double(self) }
var float: Float? { Float(self) }
var integer: Int? { Int(self) }
}
Testing
let str = "2.9"
if let value = str.double {
print(value) // "2.9\n"
} else {
print("invalid input")
}
str.prefix(1).integer // 2
str.suffix(1).integer // 9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With