简体   繁体   中英

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%. In the code this ' tipPercentSelected ' if of type String. I need to have 0.2 instead of 20% to be printed out to console when the relevant button is pressed. However, if ' tipPercentSelected ' is converted into Int it gives 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%? Thanks.

You should use a NumberFormatter with style set to percent

let tipPercent = "20%"

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

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

This prints 0.2

In your view controller it could be something like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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