如何解决在Swift,XCode 12中将小数点四舍五入到小数点后两位
我有以下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文章都建议使用这两种方法,而我在这里无法弄清楚自己做错了什么?
解决方法
将其转换为小数点后两位数字的字符串:
let yourShareString = String(format: "%.2f",yourShare)
,
您可以借助字符串插值直接在Text
内部进行操作:
struct ContentView: View {
let decimalNumber = 12.939010
var body: some View {
Text("\(decimalNumber,specifier: "%.2f")")//displays 12.94
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。