anusha hrithi
anusha hrithi

Reputation: 709

Getting error in conversion of NSNumber to String in swift

I am using CoreData to store the data.I am storing ContactNumber with the datatype of NSNumber. I am retrieving the data from DB like

  let entityDescription =
            NSEntityDescription.entityForName("Retailer",
                inManagedObjectContext: managedObjectContext)

            let request = NSFetchRequest()
            request.entity = entityDescription

            do{
                let results = try managedObjectContext.executeFetchRequest(request)


                for test in results
                {


                    print(test.valueForKey("address") as? String)
                     print(test.valueForKey("classes") as? String)
                     print(test.valueForKey("contactnumber") as! NSNumber)
                     print(test.valueForKey("landmark") as? String)
                    print(test.valueForKey("name") as? String)
                    print(test.valueForKey("outlettype") as? String)
                    print(test.valueForKey("retailername") as? String)
                     print(test.valueForKey("type") as? String)
                    print(test.valueForKey("credit") as? String)


      self.arrayOfData.append((StoringClass(retailersname: (test.valueForKey("retailername") as? String)!, names: (test.valueForKey("name") as? String)!, outlettypes: (test.valueForKey("outlettype") as? String)!, types: (test.valueForKey("type") as? String)!, credits: (test.valueForKey("credit") as? String)!, landmarks: (test.valueForKey("landmark") as? String)!, classestype: (test.valueForKey("classes") as? String)!, addresses: (test.valueForKey("address") as? String)!, contactnumbers:s)))

                }

But my problem is I am getting the ContactNumber as “-27790.000000” like that. I tried to convert the NSNumber to String but it doesn’t work for me.

 let s:String = String(format:"%f",  test.valueForKey("contactnumber")!.doubleValue)

print(s) - output:  “-27790.000000” 

Can anyone tell me what mistake I am doing.

ThanksIn Advance

Upvotes: 1

Views: 2579

Answers (2)

user3069232
user3069232

Reputation: 8995

Swift 4.0 iOS 11.x

Converting an NSNumber into a string ...

let temp:NSNumber = 5
let tempString = temp.stringValue

Upvotes: 0

Khanh Nguyen
Khanh Nguyen

Reputation: 11134

Don't use String(format:...). Use NSNumberFormatter:

let f = NSNumberFormatter()
f.maximumFractionDigits = 0
let s = f.stringFromNumber(-27790.00)!
print(s) // Output "-27790"

Upvotes: 3

Related Questions