swift - 如何在 Swift 中将包含 % 的字符串转换为 Int
问题描述
这是代码:
@IBAction func calculatePressed(_ sender: UIButton) {
let tip = tipPercentSelected.currentTitle ?? "unknown"
print(tip)
}
' tipPercentSelected '在这里表示用户可以选择的小费的百分比,例如20%。在代码中,此“ tipPercentSelected ”如果是字符串类型。当按下相关按钮时,我需要将 0.2 而不是 20% 打印到控制台。但是,如果 ' tipPercentSelected ' 被转换成 Int 它给出nil
@IBAction func calculatePressed(_ sender: UIButton) {
let tip = tipPercentSelected.currentTitle ?? "unknown"
print(tip)
let tipConverted = Int(tip)
print(tipConverted)
}
我需要什么代码才能获得 0.2 而不是 20%?谢谢。
解决方案
您应该使用NumberFormatter
设置为percent
let tipPercent = "20%"
let formatter = NumberFormatter()
formatter.numberStyle = .percent
if let tip = formatter.number(from: tipPercent) {
print(tip)
}
这打印 0.2
在您的视图控制器中,它可能是这样的
static private let formatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .percent
return formatter
}()
func calculatePressed(_ sender: UIButton) {
if let tip = tipPercentSelected.currentTitle, let tipConverted = Self.formatter.number(from: tip) {
print(tipConverted)
}
}