MonkeyBusiness
MonkeyBusiness

Reputation: 111

Migrating ObjC NSNumber code to Swift and having problems with displaying numbers.

I am migrating my ObjC app to Swift and have run into a peculiar issue.

My app reads a JSON file and builds a model from it. The numbers read from JSON used to be assigned to NSNumber. Some numbers were whole (eg.60) other had a decimal component (e.g. 60.23).

When I displayed these numbers in my app, 60 would be 60 (not 60.0) and decimals would display appropriately.

Now I am writing Swift code and assigning the numbers read from JSON to Double. Even if I use let x=String(myDouble) the number 60 will always come out 60.0

I don't want this...but I can't just format it %f because I never know if the number will be whole or have a decimal component.

Do I really need to check if it is a whole and then format it using it %f?

Am I missing something in Swift? The ObjC code behaved as I wanted by now Swift seems to be giving me decimals for whole numbers.

Upvotes: 0

Views: 84

Answers (2)

William Hu
William Hu

Reputation: 16141

FYI, here is the code in PlayGround:

let number = 60.23
String(number)

let double:Double = 60

//First way
String(NSNumberFormatter().stringFromNumber(double)!)


//Second way
let doubleString = String(double)

if doubleString.containsString(".0") {
    let length = doubleString.characters.count

    let index = doubleString.characters.indexOf(".")
    doubleString.substringToIndex(index!)
}

enter image description here

Upvotes: 1

vadian
vadian

Reputation: 285039

You could use NSNumberFormatter.

let number1 : Double = 60
let number2 = 60.23

let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = .DecimalStyle
let number1String = numberFormatter.stringFromNumber(number1) // "60"
let number2String = numberFormatter.stringFromNumber(number2) // "60.23"

Upvotes: 4

Related Questions