【发布时间】:2021-01-13 21:00:33
【问题描述】:
我有以下 Swift 代码:
var yourShare: Double {
guard let totalRent = Double(totalRent) else { return 0 }
guard let myMonthlyIncome = Double(myMonthlyIncome) else { return 0 }
guard let housemateMonthlyIncome = Double(housemateMonthlyIncome) else { return 0 }
let totalIncome = Double(myMonthlyIncome + housemateMonthlyIncome)
let percentage = Double(myMonthlyIncome / totalIncome)
let value = Double(totalRent * percentage)
return Double(round(100*value)/100)
}
然后该值显示为表单的一部分:
Section {
Text("Your share: £\(yourShare)")
}
我是 Swift 新手,我正在努力确保 yourShare 只有 2 位小数,例如150.50 美元,但目前显示为 150.50000 美元。我尝试将其四舍五入到小数点后两位是Double(round(100*value)/100),我也尝试使用无效的rounded() 方法。我搜索的其他 StackOverflow 文章建议使用这两种方法,但我无法弄清楚我在这里做错了什么?
【问题讨论】:
-
显示 $ 符号的代码在哪里?因为那是应该做的地方。使用
NumberFormatter(用于货币)。