如何实现NumberFormatter

时间:2018-03-20 20:30:15

标签: swift nsnumberformatter

我试图让我的计数器仅超过小数点后八位数。一旦达到0,最后一个数字就会消失。试图保持尾随零显示自己。

有人告诉我使用NumberFormatter。如何获取它以便secondUpdateLabel继承格式化程序?

var secondTimer = Timer()
var secondCounter: Double = 70.000000
var secondDecreaser: Double = 0.000001


func secondStartCounting(initialNumber x: Double, decreaseBy y: Double) {
    self.secondCounter = x
    self.secondDecreaser = y

    self.secondTimer.invalidate()

    let secondTimer = Timer(timeInterval: 0.38, target: self, selector: #selector(ViewController.secondUpdateTimer), userInfo: nil, repeats: true)

    RunLoop.main.add(secondTimer, forMode: .commonModes)
    self.secondTimer = secondTimer


}


@objc func secondUpdateTimer() {
    secondCounter -= secondDecreaser

    let secondUpdateLabel = secondCounter

    let formatter = NumberFormatter()
    formatter.numberStyle = NumberFormatter.Style.decimal
    formatter.usesSignificantDigits = true
    formatter.minimumFractionDigits = 8
    formatter.maximumFractionDigits = 8

    // not proper code next. just want to know how to get secondUpdateLabel to inherit the properties I applied to formatter. not sure what the next steps are 
    secondStat.text = 


}

1 个答案:

答案 0 :(得分:0)

这对我有用!

var secondTimer = Timer()
var secondCounter: Double = 70.000000
var secondDecreaser: Double = 0.000001


func secondStartCounting(initialNumber x: Double, decreaseBy y: Double) {
    self.secondCounter = x
    self.secondDecreaser = y

    self.secondTimer.invalidate()

    let secondTimer = Timer(timeInterval: 0.0000001, target: self, selector: #selector(ViewController.secondUpdateTimer), userInfo: nil, repeats: true)

    RunLoop.main.add(secondTimer, forMode: .commonModes)
    self.secondTimer = secondTimer


}


@objc func secondUpdateTimer() {
    secondCounter -= secondDecreaser

    let secondUpdateLabel = secondCounter

    let formatter = NumberFormatter()
    formatter.numberStyle = NumberFormatter.Style.decimal
    formatter.usesSignificantDigits = false
    formatter.minimumFractionDigits = 8
    formatter.maximumFractionDigits = 8

    secondStat.text = formatter.string(from: NSNumber(value: secondUpdateLabel))


}

想通了我必须将usesSignificantDigits设置为false,而我实现的最后一行代码修复了我的问题。