簡體   English   中英

Swift中如何將包含%的String轉換成Int

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

這是代碼:

@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%? 謝謝。

您應該使用樣式設置為percentNumberFormatter

let tipPercent = "20%"

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

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

這打印 0.2

在你看來 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