CAN
CAN

Reputation: 1717

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?

Upvotes: 0

Views: 1208

Answers (2)

Bhavesh Patel
Bhavesh Patel

Reputation: 596

Use below code to fetch Int from String:

let myString : String = "123"
let myInt: Int? = myString.toInt()

if myInt != nil {
    println(myInt)
}

Or if you are using Swift 2:

let myInt: Int? = Int(myString)

Upvotes: 0

Quentin Hayot
Quentin Hayot

Reputation: 7876

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.

Upvotes: 1

Related Questions