T G
T G

Reputation: 11

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, e.g. 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.

Upvotes: 0

Views: 709

Answers (1)

Joakim Danielson
Joakim Danielson

Reputation: 52013

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

Upvotes: 2

Related Questions