Search code examples
iosswiftnsnumbernsnumberformatter

Take number from string value in Swift


I have a text value that has a number and that number start with zero. For example "User number 054321" and I take this number from the text by the code below.

var phonenumber = "054321"

let myNumber = NSNumberFormatter().numberFromString("".join(phonenumber.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)))

println(myNumber) //54321

My issue is it never takes the first number which start with 0 value but it accept all other number. So please where would be my issue?


Solution

  • A number can't start with 0. Or at least, will never be displayed with a 0 as a first character. 054321 = 54321 = 0000000000054321 but at the end, it's still 54321.

    Anyway, a phone number should not be stored as a number but as a string, since it may start with a "0" or with a "+".

    TL;DR: If you want to keep your 0 at the beginning of the number, store it as a string.