SwiftDeveloper
SwiftDeveloper

Reputation: 7370

check string is int or double , with extension in swift 3

I have string extension you can see under below but only returns true for Int , I want to return it true, for All , Int and Double values only.

extension String  {
    var isnumberordouble : Bool {
        get{
            return self.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil
        }
    }
}

How can I fix it ? Any idea ? ty.

Upvotes: 0

Views: 2381

Answers (1)

vacawama
vacawama

Reputation: 154593

As @MartinR said, check if the string can be converted to an Int or a Double:

extension String  {
    var isnumberordouble: Bool { return Int(self) != nil || Double(self) != nil }
}

print("1".isnumberordouble)      // true
print("1.2.3".isnumberordouble)  // false
print("1.2".isnumberordouble)    // true

@MartinR raises a good point in the comments. Any value that converts to an Int would also convert to a Double, so just checking for conversion to Double is sufficient:

extension String  {
    var isnumberordouble: Bool { return Double(self) != nil }
}

Handling leading and trailing whitespace

The solution above works, but it isn't very forgiving if your String has leading or trailing whitespace. To handle that use the trimmingCharacters(in:) method of String to remove the whitespace (requires Foundation):

import Foundation

extension String  {
    var isnumberordouble: Bool { return Double(self.trimmingCharacters(in: .whitespaces)) != nil }
}

print("  12 ".isnumberordouble)     // true

Upvotes: 6

Related Questions