添加千位分隔符,自动(SWIFT)

我有一个代码为我的计算器添加千位分隔符,自动(SWIFT)

我怎么可以这样做,当用户将输入他将自动空格隔开的数字?

我一直在试图寻找了很久的答案,但没有适合它被显示马上


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

}

}

错误

var stillTyping = false 

var dotIsPlaced = false

var firstOperand: Double = 0

var secondOperand: Double = 0

var operationSign: String = ""

回答:

最好将您的值累加到单独的字符串中,该字符串没有应用格式化而不是使用文本字段作为数据模型。然后可格式化十进制和根据需要使用在标签显示它一个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)

}

回答:

这是NumberFormatter s为用于

let formatter = NumberFormatter() 

formatter.numberStyle = .decimal

if let newNumber = formatter.number(from: displayResultLabel.text! + number){

displayResultLabel.text = formatter.string(from: newNumber)

}

注意NumberFormatter走吧两种方式,你可以(并且可能应该)用它来从分析数字字符串也是

以上是 添加千位分隔符,自动(SWIFT) 的全部内容, 来源链接: utcz.com/qa/259902.html

回到顶部