swift - 在 Swift 中通过 String(format:...) 将十进制转换为字符串
问题描述
你能帮我解决以下情况吗:当我尝试“eachPersonPays”从十进制转换为字符串时,我收到错误“参数类型'十进制'不符合预期的类型'CVarArg'”。当我确认修复为“as CVarArg”时,我没有计算出“totalBill”。
我应该怎么做:totalBill = String(format: "%.2", eachPersonPays) 这样我就可以计算出totalBill。
@IBAction func calculatePressed(_ sender: UIButton) {
bill = billTextField.text!
if (Decimal(string: bill) != nil) == true {
let eachPersonPays: Decimal = (Decimal(string: bill)! * tip) / Decimal(string: numberOfPeople)!
totalBill = String(format: "%.2", eachPersonPays)
print(totalBill)
self.performSegue(withIdentifier: "goToResult", sender: self)
} else {
billTextField.text = "input bill amount"
PS我希望我能正确解释我遇到的问题。
解决方案
@
缺少数字对象的说明符:format: "%@.2"
顺便一提
if (Decimal(string: bill) != nil) == true
非常不迅速,有可选绑定
if let decimalBill = Decimal(string: bill),
let decimalNumberOfPeople = Decimal(string: numberOfPeople) {
let eachPersonPays = decimalBill * tip / decimalNumberOfPeople
let totalBill = String(format: "%@.2", eachPersonPays as CVarArg) // or as NSNumber
}
推荐阅读
- java - 什么是 BuildConfig.APPLICATION_ID
- ios - 无法加载 plist 文件,错误无法解析 Plist 数据类型:键
- vmware - 无法连续 ping 虚拟机
- angular - Angular 如何使用 Golang 和 websockets 管理 URL?
- android - 在android中解析Json的问题
- sql - 如何按日期查询结果调整 SQL 聚合以合并某些列存在空值的同一级别的值
- android - java.lang.NoClassDefFoundError:org.springframework.web.util.UriTemplate
- keras - Keras:如何检查哪个操作没有定义渐变?
- pepper - Pepper:将变量从 Python 传递到 Web JS 并在 html 中显示
- image - 如何使用matlab将轮廓图保存到图像(.jpg)?