Jeb Nicholson Jeb Nicholson - 1 year ago 79
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:


I want it to display as just:


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 {

Thanks in advance,
-Another Nooby user

Answer Source
    let number1 = 1.0
    let number2 = 1.2

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

    let str2 = String(format: number2 == floor(number2) ? "%.0f":"%.1f", number2)
    //prints 1.2
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download