在 Swift、XCode 12 中将双精度舍入到小数点后两位

Jor*_*993 5 number-formatting swift

我有以下 Swift 代码:

\n
var yourShare: Double {\n        guard let totalRent = Double(totalRent) else { return 0 }\n        guard let myMonthlyIncome = Double(myMonthlyIncome) else { return 0 }\n        guard let housemateMonthlyIncome = Double(housemateMonthlyIncome) else { return 0 }\n        let totalIncome = Double(myMonthlyIncome + housemateMonthlyIncome)\n        let percentage = Double(myMonthlyIncome / totalIncome)\n        let value = Double(totalRent * percentage)\n\n        return Double(round(100*value)/100)\n    }\n    \n
Run Code Online (Sandbox Code Playgroud)\n

然后该值显示为表单的一部分:

\n
  Section {\n               Text("Your share: \xc2\xa3\\(yourShare)")\n          }\n
Run Code Online (Sandbox Code Playgroud)\n

我是 Swift 新手,我试图确保yourShare只有 2 位小数,例如 $150.50,但目前它显示为 $150.50000。我尝试将其四舍五入到小数点后两位,Double(round(100*value)/100)并且我也尝试使用该rounded()方法,但不起作用。我搜索的其他 StackOverflow 文章建议这两种方法,但我无法弄清楚我在这里做错了什么?

\n

小智 6

将其转换为小数点后2位的字符串:

let yourShareString = String(format: "%.2f", yourShare)
Run Code Online (Sandbox Code Playgroud)


fin*_*bel 3

您可以Text借助字符串插值直接在内部完成此操作:

struct ContentView: View {
    let decimalNumber = 12.939010

    var body: some View {
        Text("\(decimalNumber, specifier: "%.2f")")//displays 12.94
    }
}
Run Code Online (Sandbox Code Playgroud)