Search code examples
iosswifttimer

When trying to make a countdown by 0.10 it prints wrong thing


I'm trying to make a countdown timer for iOS and when I try to make it go down by 0.10 and when I run the program it after like 8.2, 8.1, it starts printing like this 7.900000000, 7.800000012 something like this.

Here what it prints

And also it's supposed to stop at 0 but

stops here

But it works perfectly when making it go down by 0.25, or .5 or 1.

Here is my code.

var seconds = 10.0
var timer = Timer()

@IBAction func startPressed(_ sender: Any) {
    startBtn.isHidden = true
    clickedTxt.isHidden = false
    numClicked.isHidden = false
    tapView.isEnabled = true
    timerTxt.isHidden = false
    secs.isHidden = false

    timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(ViewController.counter), userInfo: nil, repeats: true)
}

func counter()
{
    if(seconds > 0.0)
    {
        seconds -= 0.1
        secs.text = "\(seconds)"
    } else {
        timer.invalidate()
    }
}

Solution

  • You're seeing an effect of the way floating point numbers are formatted, essentially. And you can read more about that in the other question rmaddy pointed you to.

    I suspect you mostly want to format that label nicely. In that case you can do something like:

    secs.text = String(format:"%.1f", secs)
    

    where you replace ".1" with however many places after the decimal you want.