jlcreator
jlcreator

Reputation: 1

Assess any decimal places for a number and change it to integer in Swift

For a calculator app (Swift, iOS), I use Double numbers in my logics of calculation.

On UI, the label where the number (in String) appears, it would appears as for instance 7.0 after calculation. I want it to show just 7 if there’s no decimal place, i.e. an integer.

How do I do that in the background before converting the number to a String?

Upvotes: 0

Views: 187

Answers (1)

matt
matt

Reputation: 535989

Use a NumberFormatter. It presents 7.0 as the string "7", but 7.1 as the string "7.1".

This is just a test to show the behavior:

    let f = NumberFormatter()
    f.usesSignificantDigits = true
    let d : Double = 7.0
    print(f.string(from: d as NSNumber)) // 7
    let d2 : Double = 7.1
    print(f.string(from: d2 as NSNumber)) // 7.1

Upvotes: 1

Related Questions