Check if a string is a valid number in Swift
In this tutorial, we will learn how to check if a string contains only numbers or digits in Swift.
I have created a Swift function that will return true if all the characters of the string make a valid number.
It will also return true if the string is a decimal number with a floating point.
For example:
If the string is “o
” it will return true. If the string is a negative number like “-96
” it will also return true.
In case of “54.65
” it will also return true.
But if the string is something like “hgjhgajk
” or “6787sjhh
” it will return false.
The logic that we are going to use:
We will try to convert our string to double, if the number can be converted to double we can say that the string contains only numbers.
The good part is that it also works on decimal numbers.
Swift program to check if a string is a number or not
Take a look at the program below:
func isStringNumer(string: String) -> Bool { return Double(string) != nil } print(isStringNumer(string: "4545.85"))
Output:
True
If you wish, you can try with different inputs. I have tested with a lot of inputs like 45465..887 (invalid number), negative numbers, large numbers etc.
Check if a string is a number or not using Regex (Regular expression)
I am pretty sure that this expression will detect all types of numbers. No matter if the number is integer, floating, negative…
import Foundation func isNumberRegex(string: String) -> Bool { let regex = try? NSRegularExpression(pattern: "^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$") return regex?.firstMatch(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count)) != nil } print(isNumberRegex(string: "-5654.45"))
Output:
True
Also read: Count number of occurrences of a character in a string in Swift
Leave a Reply