You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何将带有%符号的字符串转换为对应的小数数值

直接转换Int得到nil的核心原因是tip字符串中包含%特殊字符,无法被Int类型的默认构造器识别。你可以按以下步骤处理得到预期的0.2结果:

  • 先移除字符串中的%符号
  • 将清理后的纯数字字符串转换为数值类型
  • 除以100得到百分比对应的小数比例

完整可运行代码如下:

@IBAction func calculatePressed(_ sender: UIButton) {
    let tip = tipPercentSelected.currentTitle ?? "unknown"
    print(tip)
    // 移除%符号
    let cleanedTip = tip.replacingOccurrences(of: "%", with: "")
    // 转换为数值,异常兜底
    guard let tipValue = Double(cleanedTip) else {
        print("百分比格式无效")
        return
    }
    let tipConverted = tipValue / 100
    print(tipConverted)
}

如果你的业务场景中百分比都是整数,也可以先转Int再做计算,使用Double转换可兼容12.5%这类带小数的百分比场景。

内容的提问来源于stack exchange,提问作者T G

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 03:09:01