在 Swift、XCode 12 中将双精度四舍五入到小数点后两位
Rounding a double to 2 decimal places in 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 美元。我尝试将其四舍五入到小数点后 2 位是 Double(round(100*value)/100)
并且我还尝试使用无效的 rounded()
方法。我搜索的其他 Whosebug 文章建议了这两种方法,但我无法弄清楚我在这里做错了什么?
转换成小数点后2位的字符串:
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
}
}
我有以下 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()
方法。我搜索的其他 Whosebug 文章建议了这两种方法,但我无法弄清楚我在这里做错了什么?
转换成小数点后2位的字符串:
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
}
}