How to check if text contains only numbers?

IosSwift

Ios Problem Overview


I've tried many cases, but none work for me. I tried:

if resultTitles[indexPath.row].rangeOfCharacterFromSet(badCharacters) == nil {
    let badCharacters = NSCharacterSet.decimalDigitCharacterSet().invertedSet
    print("Index: \(indexPath.row)")
}

also tried to

if ((resultTitles[0].toInt()) != nil) {
    print("ERROR")
}

So, how can I check that my text contains only numbers?

Ios Solutions


Solution 1 - Ios

I find this solution, in Swift 3, to be cleaner

import Foundation

CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: yourString))

Solution 2 - Ios

You just need to check whether the Set of the characters of your String is subset of the Set containing the characters from 0 to 9.

extension String {
    var isNumeric: Bool {
        guard self.characters.count > 0 else { return false }
        let nums: Set<Character> = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
        return Set(self.characters).isSubset(of: nums)
    }
}

"".isNumeric // false
"No numbers here".isNumeric // false
"123".isNumeric // true
"Hello world 123".isNumeric // false

Solution 3 - Ios

Expanding on the fantastic work from Luca above, here is the answer given written by way of Swift 5.

extension String {
    var isNumeric: Bool {
        guard self.count > 0 else { return false }
        let nums: Set<Character> = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
        return Set(self).isSubset(of: nums)
    }
}

Solution 4 - Ios

We have to check whether every character of the string is a digit or not and string must not be empty.

extension String {
   var isNumeric: Bool {
     return !(self.isEmpty) && self.allSatisfy { $0.isNumber }
   }
}

allSatisfy(_ predicate: (Character) throws -> Bool) rethrows -> Bool is a method which returns a Boolean value indicating whether every element of a sequence satisfies a given predicate.

For reference: https://developer.apple.com/documentation/swift/array/2994715-allsatisfy

Example:

  1. let string = "123" string.isNumeric ---- returns true

  2. let string_One = "1@3" string_One.isNumeric ---- returns false

Solution 5 - Ios

This may help you.

 let string  = "536783"
    let num = Int(string);
    
    if num != nil {
        print("Valid Integer")   
    }
    else {
        print("Not Valid Integer")
    }

Solution 6 - Ios

It depends what you mean by numbers. If you mean 0-9 then you can use this:

let numbersSet = CharacterSet(charactersIn: "0123456789")

let textCharacterSet = CharacterSet(charactersIn: "123")

if textCharacterSet.isSubset(of: numbersSet) {
    print("text only contains numbers 0-9")
} else {
    print("text contains invalid characters")
}

If you mean all kinds of different ways of specifying numbers then you can use CharacterSet.decimalDigits which contains all kinds of ways of specifying numbers.

Solution 7 - Ios

Your first options works for me in playground. Check it again. Assuming str = resultTitles[indexPath.row]

func isStringContainsOnlyNumbers(string: String) -> Bool {
    return string.rangeOfCharacterFromSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet) != nil
}

// Now let's try to use it

let str = "Hello, playground"

if (isStringContainsOnlyNumbers(str)) {
    print("\(str) has illegal characters")  // "Hello, playground has illegal characters"
}
else {
    print("\(str) has only number")
}

let numStr = "332432"

if (isStringContainsOnlyNumbers(numStr)) {
    print("\(numStr) has illegal characters")
}
else {
    print("\(numStr) has only number")   // "332432 has only number\n"
}

Solution 8 - Ios

Some of the codes above will work only with Arabic Digits ( 0, 1 , 2 ,...). However, it won't work with other digits format ( like Hindi one which is used in Arabic countries, ١, ٢ , ٣ , or that one used in Chinese ..)

I have tested the below code ( taken from the codes above with some correction for is Digits with different numbers format ( Chinese, Hindi used in Arabic , ...).

extension String {

	var isNumeric : Bool { return CharacterSet(charactersIn: self).isSubset(of: CharacterSet.decimalDigits)
	}
	
	var isDigits : Bool {
		guard !self.isEmpty else { return false }
		let containsNonNumbers = self.contains { !$0.isNumber }
		return !containsNonNumbers
	}
}

Solution 9 - Ios

Try with this

let numbersTest = resultTitles[indexPath.row]
        if let number = Int(numbersTest){
            print(number)//contains onlyy number
        }else{
            print("notnumber")//Not number
        }

Solution 10 - Ios

Try this:

if ( [resultTitles[indexPath.row] isMatchedByRegex:@"^(?:|0|[1-9]\\d*)(?:\\.\\d*)?$"] ) {
  //Text is only numeric
}
else
{
  //Text is not only numeric
}

Solution 11 - Ios

The cleanest Swift way in my opinion is this:

extension String {
  var isDigits: Bool {
    guard !self.isEmpty else { return false }
    return !self.contains { Int(String($0)) == nil }
  }
}

"123".isDigits // returns true
"12d".isDigits // returns false

Solution 12 - Ios

based on 'Cristina De Rito' solution here is a little playgrud routine for checking results, you can add your own CharacterSet (swift 5)

var arr_IsStringNumberOnly:[String] = ["123", "456.7", "890,1", "1'234", "", "abc", "def3", "xyz 4", "5 äöü"]
for i in 0..<arr_IsStringNumberOnly.count {
    //the code w/o 'nil'
    CharacterSet.init(arrayLiteral: "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ",", ".", "'" ).isSuperset(of: CharacterSet(charactersIn: arr_IsStringNumberOnly[i]))
    
    //the code with handling 'nil' (nil dosent work in test array)
    //CharacterSet.init(arrayLiteral: "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ",", ".", "'" ).isSuperset(of: CharacterSet(charactersIn: arr_IsStringNumberOnly ?? "abc")) //if empty assume it's text

    //the code with handling 'nil' (nil dosent work in test array)
    //CharacterSet.init(arrayLiteral: "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ",", ".", "'" ).isSuperset(of: CharacterSet(charactersIn: arr_IsStringNumberOnly ?? "123")) //if empty assume it's numeric

    
    //presentation:
    print("arr_IsStringNumberOnly[i]: \(arr_IsStringNumberOnly[i]) \t '\(CharacterSet.init(arrayLiteral: "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ",", ".", "'" ).isSuperset(of: CharacterSet(charactersIn: arr_IsStringNumberOnly[i])) )'")

}

Presents:

  • arr_IsStringNumberOnly[i]: 123 'true'
  • arr_IsStringNumberOnly[i]: 456.7 'true'
  • arr_IsStringNumberOnly[i]: 890,1 'true'
  • arr_IsStringNumberOnly[i]: 1'234 'true'
  • arr_IsStringNumberOnly[i]: 'true'
  • arr_IsStringNumberOnly[i]: abc 'false'
  • arr_IsStringNumberOnly[i]: def3 'false'
  • arr_IsStringNumberOnly[i]: xyz 4 'false'
  • arr_IsStringNumberOnly[i]: 5 äöü 'false'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser4809833View Question on Stackoverflow
Solution 1 - IosCristina De RitoView Answer on Stackoverflow
Solution 2 - IosLuca AngelettiView Answer on Stackoverflow
Solution 3 - IosBrandon AView Answer on Stackoverflow
Solution 4 - IosNeelima DarapureddyView Answer on Stackoverflow
Solution 5 - IostechnerdView Answer on Stackoverflow
Solution 6 - IosBlair McArthurView Answer on Stackoverflow
Solution 7 - IosOssirView Answer on Stackoverflow
Solution 8 - IosHusseinView Answer on Stackoverflow
Solution 9 - IosManuelView Answer on Stackoverflow
Solution 10 - IosThomasView Answer on Stackoverflow
Solution 11 - IosFiras SafaView Answer on Stackoverflow
Solution 12 - IosRvdHView Answer on Stackoverflow