2017-04-20 21 views
1

我想爲iOS做一個倒計時計時器,當我試圖使它下降0.10和當我運行程序後像8.2,8.1,它開始打印像這樣7.900000000,7.800000012這樣的東西。當試圖通過0.10倒計時它打印錯誤的東西

Here what it prints

而且也是它應該停止在0,但

stops here

但它完美的作品時,使它變爲下跌0.25,或0.5或1

這裏是我的代碼。

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() 
    } 
} 
+3

閱讀http://stackoverflow.com/questions/588004/is-floating-point-math-broken?s=1|16.6051 – rmaddy

回答

1

你看到浮點數格式化的效果,本質上。你可以在the other question rmaddy pointed you to瞭解更多。

我懷疑你大多想要很好地格式化該標籤。在這種情況下,您可以執行類似以下操作:

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

其中將「.1」替換爲小數點後的任意位置。

+0

這解決了輸出問題,但它沒有解決停止' 0'。 – vacawama

+1

而不是測試它是否大於0.0,測試它是否大於您能夠容忍的錯誤值。就像'if(seconds> 0.0001)'。 –

+0

謝謝亞倫黃金和價格林戈,它現在的作品。 –

相關問題