Jeb Nicholson Jeb Nicholson - 1 month ago 7
Swift Question

How do I convert Float to Int When Necessary?

So, I'm pretty new to swift and Xcode and might be missing something obvious, but I've done a bit of research, and can't find my answer.
My code is:

for number in currentList {
listPreview.text = "\(listPreview.text!) \(String(number))"
}


The problem is, the Numbers in currentList are Floats. But if my user were to input a number that isn't a float, it will display as:

"UsersNumber".0


I want it to display as just:

"UsersNumber"


However, if the number the user gave me was a float, say... 1.2, I would still want it to display as 1.2 .

is there some kind of extension that can do this?

Like an if-statement saying

if number.isUselessFloat {
code
}


Thanks in advance,
-Another Nooby user

Answer
    let number1 = 1.0
    let number2 = 1.2

    let str = String(format: number1 == floor(number1) ? "%.0f":"%.1f", number1)
    print(str)
    //prints 1

    let str2 = String(format: number2 == floor(number2) ? "%.0f":"%.1f", number2)
    print(str2)
    //prints 1.2