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
相关产品推荐
相关产品推荐

