String to NSNumber in Swift
Asked Answered
V

9

73

I found a method to convert String to NSNumber, but the code is in Objective-C. I have tried converting it to Swift but it is not working.

The code I am using:

NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *myNumber = [f numberFromString:@"42222222222"];

and in Swift I am using it in this way:

var i = NSNumberFormatter.numberFromString("42")

But this code is not working. What am I doing wrong?

Vansickle answered 19/2, 2015 at 11:53 Comment(1)
try this NSNumberFormatter().numberFromString("42")!.doubleValueUnblock
H
162

Swift 3.0

NSNumber(integer:myInteger) has changed to NSNumber(value:myInteger)

let someString = "42222222222"
if let myInteger = Int(someString) {
    let myNumber = NSNumber(value:myInteger)
}

Swift 2.0

Use the Int() initialiser like this.

let someString = "42222222222"
if let myInteger = Int(someString) {
    let myNumber = NSNumber(integer:myInteger)
    print(myNumber)
} else {
    print("'\(someString)' did not convert to an Int")
}

This can be done in one line if you already know the string will convert perfectly or you just don't care.

let myNumber = Int("42222222222")!

Swift 1.0

Use the toInt() method.

let someString = "42222222222"
if let myInteger = someString.toInt() {
    let myNumber = NSNumber(integer:myInteger)
    println(myNumber)
} else {
    println("'\(someString)' did not convert to an Int")
}
Hepta answered 19/2, 2015 at 11:55 Comment(9)
my number is long long not interger and replacing interger to longlong shows error?Vansickle
are you saying that your string is not in this format: "42" ?Hepta
Perhaps you could update your question with a string in the format you want?Hepta
Swap 2.0 and 1.0 answers, placing 2.0 on top.Castrate
@Castrate feel free to edit my answer if you feel it could be structured better.Hepta
If I do it will probably be declined as "no improvement" (-:Castrate
You should be really careful with using Int and Int64 - if the number can be bigger than Int32 and your app can run on iPhone 5 or older, use Int64 and not IntZoochore
They couldn't bang our asses any other way, so they made swift... Putting us in a position to ask such simple questions.Semi
Keep in mind, the string may contain double value, not int. In this case you should use if let myInteger = Double(someString)Niobium
G
16

Or do it just in one line:

NSNumberFormatter().numberFromString("55")!.decimalValue
Gertiegertrud answered 21/7, 2015 at 18:32 Comment(2)
Like David Berry commented below, be careful with creating NSNumberFormatters like this as they are expensive to create. Better caching or using a singleton if using the same formatter more than once.Electrotherapeutics
Has been updated for Swift 5: NumberFormatter().number(from: "55")!Rigid
A
9

In latest Swift:

let number = NumberFormatter().number(from: "1234")
Aleksandropol answered 4/9, 2019 at 8:2 Comment(0)
C
8

Swift 2

Try this:

var num = NSNumber(int: Int32("22")!)

Swift 3.x

 NSNumber(value: Int32("22")!)
Clasp answered 4/8, 2016 at 11:9 Comment(2)
with Swift 3.x this is now.. NSNumber.init( value: Int32("22")!)Tapley
no need to initialize with '.init'. simply write: NSNumber(value: Int32("22")!)Osmunda
W
6

You can use the following code if you must use NSNumberFormatter. It's simpler to use Wezly's method.

let formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle;
if let number = formatter.numberFromString("42") {
    println(number)
}
Wreckage answered 19/2, 2015 at 11:59 Comment(1)
Note also that NSNumberFormatter is expensive to create, and should be cached whenever possible instead of being created every time it's used.Proven
T
3

Swift 5

let myInt = NumberFormatter().number(from: "42")
Twila answered 1/6, 2021 at 7:6 Comment(0)
B
2

I do use extension in swift 3/4 and it's cool.

extension String {
    var numberValue: NSNumber? {
        if let value = Int(self) {
            return NSNumber(value: value)
        }
        return nil
    }
}

and then just use following code:

stringVariable.numberValue

What is cool is that you don't need a chain of if statements to unwrap the optional values. For instance,

if let _ = stringVariable, let intValue = Int(stringVariable!) {
    doSomething(NSNumber.init(value: intValue))
}

can be replaced by:

doSomething(stringVariable?.numberValue)
Batman answered 18/4, 2018 at 1:14 Comment(0)
P
-1

("23" as NSString).integerValue ("23.5" as NSString).doubleValue

and so on .

Punch answered 16/4, 2020 at 3:0 Comment(0)
D
-5

Try Once

let myString = "123"
let myInt = NSNumber(value: Int(myString) ?? 0)
Droppings answered 18/10, 2016 at 12:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.