自动添加千位分隔符(Swift)

时间:2017-12-03 07:26:01

标签: ios swift xcode

我的计算器代码

我怎么能这样做,当用户输入数字时,他会自动用空格分隔?

我一直试图找到一个答案很长一段时间,但没有任何东西适合立即显示

gif

var currentInput: Double {
    get {
        return Double (displayResultLabel.text!)!
    }
    set {
        let value = "\(newValue)"
        let ValueArray = (value.components(separatedBy:"."))
        if ValueArray[1] == "0" {
            displayResultLabel.text = "\(ValueArray[0])"
        } else {
            displayResultLabel.text = "\(newValue)"
        }
        stillTyping = false
    }
}
@IBAction func numberPressed(_ sender: UIButton) {
    let number = sender.currentTitle!

    if stillTyping {
        if (displayResultLabel.text?.characters.count)! < 14 {
            displayResultLabel.text = displayResultLabel.text! + number
        }
    } else {
        displayResultLabel.text = number
        stillTyping = true
    }
}

然后发生了什么:

@IBAction func numberPressed(_ sender: UIButton) {
    let number = sender.currentTitle!

    if stillTyping {
        if (displayResultLabel.text?.characters.count)! < 14 {
            let formatter = NumberFormatter()
            formatter.numberStyle = .decimal
            let newNumber = NSNumber(value: Double(displayResultLabel.text! + number)!)

            displayResultLabel.text = formatter.string(from: newNumber)
        }
    } else {
        displayResultLabel.text = number
        stillTyping = true
    }
}

错误 enter image description here

var stillTyping = false
var dotIsPlaced = false
var firstOperand: Double = 0
var secondOperand: Double = 0
var operationSign: String = ""

2 个答案:

答案 0 :(得分:1)

这是NumberFormatter的用途

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
if let newNumber = formatter.number(from: displayResultLabel.text! + number){
    displayResultLabel.text = formatter.string(from: newNumber)
}

请注意,NumberFormatter是双向的,您可以(也可能应该)使用它们来解析字符串中的数字

答案 1 :(得分:1)

最好将您的值累积在一个单独的字符串中,该字符串没有应用格式,而不是使用文本字段作为您的数据模型。然后,您可以使用NumberFormatter

根据需要格式化小数并在标签中显示
let formatter: NumberFormatter = {
   let formatter = NumberFormatter()
   formatter.numberStyle = .decimal
   return formatter
}()

var currentInput: String = "0" {
    didSet {
        self.displayResultLabel?.text = self.currentDisplay
}

var currentValue: Double {
    return Double(self.currentInput) ?? 0
}

var currentDisplay: String {
    return formatter.string(from: NSNumber(value:self.currentValue)) ?? "0"
}

func addDigit(_ digit: Int) {
    if currentInput.count < 14 {
        let newValue = self.currentValue * 10 + Double(digit)
        self.currentInput = "\(newValue)"
    }
}

@IBAction func numberPressed(_ sender: UIButton) {
    guard let digit = Int(sender.currentTitle!) else {
        return
    }

    self.addDigit(digit)
}