【问题标题】:How to convert a String that contains % into an Int in Swift如何在 Swift 中将包含 % 的字符串转换为 Int
【发布时间】:2021-10-24 20:45:40
【问题描述】:

代码如下:

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

【问题讨论】:

  • 你为什么首先使用字符串?当用户选择小费百分比时,只需保留该值的参考。仅将值转换为字符串以将其显示给用户。
  • @LeoDabus 问题是它不是代码的开头,所以在这个阶段面临字符串转换的问题。请参阅下面的 Joakim 提供的答案是可以的。
  • 从来没有说过它行不通。我的问题是为什么当用户选择百分比时它会生成一个字符串而不是百分比值?我的意思是你应该使用数字格式化程序来生成要显示的字符串而不是解析它。
  • @LeoDabus “为什么当用户选择百分比时它会生成一个字符串而不是百分比值?” - 这只是一个训练代码,是训练任务的一部分)
  • 无论如何。顺便说一句,您在问如何将其转换为 Int。您需要在解析百分比值后乘以 100,然后将浮点强制转换为整数值。

标签: swift string integer percentage


【解决方案1】:

您应该使用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)
    }
}

【讨论】:

  • @ Joakim Danielson 您的代码的第一部分工作得很好!谢谢
  • 嘿嘿,.dropLast 方法也可以正常工作,因此首先要去掉百分号和除以 100
  • 使用 NumberFormatter 比手动更改字符串要好得多
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-28
  • 2016-03-19
  • 2012-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多