Korpel
Korpel

Reputation: 2458

NSNumberFormatter, numberFromString and it's behaviour

I would like to ask if this is the behaviour the NSNumberFormatter should have. Let's say i have a String that not full on numbers ex: 123809d 328190 jdksla. Why when i use numberFromString i do get nil instead of the number?(i do include intValue, or doubleValue at the end btw). Isn't that how NSNumberFormatter should work or you must give a number converted to string 100% of times in order to just work? here is the code for the above :

import UIKit

let p = "123809d328190jdksla"
let k = NSNumberFormatter().numberFromString(p)?.doubleValue



k = nil

Upvotes: 0

Views: 313

Answers (2)

Abizern
Abizern

Reputation: 150625

Here's one way to do this:

// First, here's the string
let mixedString = "123809d328190jdksla"

// For convenience let's define the charaterset of all non-numeric characters.
// We do this by inverting the numeric character set.
let nonDecimalCharacterSet = NSCharacterSet.decimalDigitCharacterSet().invertedSet

// Now the meat of the method
let numericStrings = mixedString
    .componentsSeparatedByCharactersInSet(nonDecimalCharacterSet) // 1
    .filter { !($0.isEmpty) }                                     // 2
    .reduce("", combine: +)                                       // 3

// 1 Split the string into an array of strings by non-decimal characters
// 2 remove empty strings
// 3 combine the array of strings into a single string

// Now turn the string into a number
let number = Int(numericString)

You can put all this into a playground to see how it works out.enter image description here

Upvotes: 1

vadian
vadian

Reputation: 285092

It's the correct behavior

From the documentation of numberFromString:

Return Value
An NSNumber object created by parsing string using the receiver’s format. Returns nil if there are no numbers in the passed string.

PS: What number representation of jdksla do you expect?

Upvotes: 0

Related Questions