Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string is a valid double value in Swift

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
}
like image 809
Michael Voccola Avatar asked May 19 '15 02:05

Michael Voccola


People also ask

Is Double A Swift?

The Double data type is the standard Swift way of storing decimal numbers such as 3.1, 3.14159 and 16777216.333921.

What is double value in Swift?

Swift provides two signed floating-point number types: Double represents a 64-bit floating-point number. Float represents a 32-bit floating-point number.

How do I convert a string to a double in Swift?

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")!)

Is whole number Swift?

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”.


2 Answers

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
     }
}
like image 66
andriys Avatar answered Sep 28 '22 10:09

andriys


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
like image 27
Leo Dabus Avatar answered Sep 28 '22 08:09

Leo Dabus