Search code examples
swifttimetimeruilabel

How can I change time format of a label ? Swift


In my App I want to show the user the Time he needed. At the moment it looks like this: enter image description here This is the actual code:

if counter <= 59.0 {
            resultTimeLabel.text = String(format: "%.1", counter)
            resultTimeLabel.text = "in \(counter) seconds"
        }
        if counter >= 60.0 {
            let minutes = counter / 60.0
            resultTimeLabel.text = String(format: "%.1", counter)
            resultTimeLabel.text = "in \(minutes) minutes"

Which format is the right one to make it looks like: 1.5 and not 1.5000000023


Solution

  • The issue there is that you are assigning a new string over the previous formatted string and it is missing an "f" in your string format:

    if counter < 60 {
        resultTimeLabel.text = "in " + String(format: "%.1f", counter) + " seconds"
    }
    else 
    if counter >= 60 {
        let minutes = counter / 60.0
        resultTimeLabel.text = "in " + String(format: "%.1f", minutes) + " minutes"