我有以下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。我试图将其舍入到小数点的2位,这是Double(round(100*value)/100),我还尝试使用rounded()方法,但没有起作用。我搜索的其他StackOverflow文章提出了这两种方法,但我无法搞清楚我在这里做错了什么?
发布于 2020-09-28 09:47:05
您可以直接在Text中使用字符串内插的方法来完成该操作:
struct ContentView: View {
let decimalNumber = 12.939010
var body: some View {
Text("\(decimalNumber, specifier: "%.2f")")//displays 12.94
}
}发布于 2020-09-28 09:45:51
将其转换为小数点后有2位数字的字符串:
let yourShareString = String(format: "%.2f", yourShare)https://stackoverflow.com/questions/64099456
复制相似问题