简体   繁体   English

Swift中如何将包含%的String转换成Int

[英]How to convert a String that contains % into an Int in Swift

Here is the code:这是代码:

@IBAction func calculatePressed(_ sender: UIButton) {
    let tip = tipPercentSelected.currentTitle ?? "unknown"
    print(tip)
    }

' tipPercentSelected ' here represents an amount of tips in % that can be chosen by the user, eg 20%.这里的' tipPercentSelected '表示可以由用户选择的以%为单位的提示量,例如20%。 In the code this ' tipPercentSelected ' if of type String.在代码中,这个“ tipPercentSelected ”如果是字符串类型。 I need to have 0.2 instead of 20% to be printed out to console when the relevant button is pressed.当按下相关按钮时,我需要将 0.2 而不是 20% 打印到控制台。 However, if ' tipPercentSelected ' is converted into Int it gives nil但是,如果将“ tipPercentSelected ”转换为 Int 它会给出nil

@IBAction func calculatePressed(_ sender: UIButton) {
    let tip = tipPercentSelected.currentTitle ?? "unknown"
    print(tip)
    let tipConverted = Int(tip)
    print(tipConverted)
    
    }

What code do I need to get 0.2 instead of 20%?我需要什么代码才能获得 0.2 而不是 20%? Thanks.谢谢。

You should use a NumberFormatter with style set to percent您应该使用样式设置为percentNumberFormatter

let tipPercent = "20%"

let formatter = NumberFormatter()
formatter.numberStyle = .percent

if let tip = formatter.number(from: tipPercent) {
    print(tip)
}

This prints 0.2这打印 0.2

In your view controller it could be something like this在你看来 controller 可能是这样的

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)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM