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
}
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 9 or later • Swift 4 or later
You can use Double initialiser StringProtocol to create an extension and use it to check if your string is a valid double as follow:
extension StringProtocol {
var double: Double? {
return Double(self)
}
var float: Float? {
return Float(self)
}
var integer: Int? {
return 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
Why not let it return false
? Or true
of course.
extension String {
func isInt() -> Bool {
if let intValue = Int(self) {
if intValue >= 0 {
return true
}
}
return false
}
func isFloat() -> Bool {
if let floatValue = Float(self) {
if floatValue >= 0 {
return true
}
}
return false
}
func isDouble() -> Bool {
if let doubleValue = Double(self) {
if doubleValue >= 0 {
return true
}
}
return false
}
func numberOfCharacters() -> Int {
return self.characters.count
}
}
Here is my function:
func je_numerik(text:Character)->Bool //en znak
{
if((text=="0")||(text=="1")||(text=="2")||(text=="3")||(text=="4")||(text=="5")||(text=="6")||(text=="7")||(text=="8")||(text=="9")){
return true
}
else
{
return false
}
}
func je_stevilka(text: String)->Bool
{
var pika:Character
pika="."
var je_stevilka=true
//var znaki = Character(text)
var znaki=Array(text)
var stevilo_znakov=znaki.count
if(stevilo_znakov==0)
{
je_stevilka=false
}
else
{
if(stevilo_znakov==1)
{
if(je_numerik(znaki[0]))
{
je_stevilka=true
}
else
{
je_stevilka=false
}
}
else
{
if((je_numerik(znaki[0])) && (!((znaki[0]=="0")&&((znaki[1]=="0"))))&&(!((znaki[0]=="0")&&((je_numerik(znaki[1]))))))
{
var je_pika=false
for var i = 0; i < stevilo_znakov; i++
{
if(je_numerik(znaki[i])||(znaki[i]==pika))
{
if(znaki[i]==pika)
{
if(je_pika)
{
je_stevilka=false
}
else
{
je_pika=true
if(stevilo_znakov==(i+1))
{
je_stevilka=false
}
}
}
}
else
{
je_stevilka=false
}
}
}
else
{
je_stevilka=false
}
}
}
return je_stevilka
}
Just call it like this:
var check_if_is_number=je_stevilka(numberText)